微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在鼠标悬停时突出显示单行

当鼠标悬停在该行(在该行中的任何单词上)时,我想更改多行段落中单行的背景颜色 – 这可以使用JQuery / JS实现吗?

如果是这样,怎么样?

编辑:
为了澄清,我希望一旦鼠标悬停在任何行上就会突出显示.
该脚本必须动态隔离光标所在的行,并在鼠标悬停时对其应用临时样式.

编辑2:
一张图片
http://i46.tinypic.com/nvv9y.png

解决方法:

这是一场艰苦的战斗,但我提出了一种方法来做到这一点,根本不需要容器上的样式(包括它的字体,对齐等).

这不是一个完美的解决方案,但希望它适用于您的目的.

var
    //Keeps the content (individual spans) as they are built.
    $keeper = $("<div>"),
    //Used to measure span width for comparison to container.
    $measurer = $("<div>"),
    //The container of the text content
    $p = $("p"),
    //An individual line of the content
    $line = $("<span>").appendTo($measurer),

//make this "invisible," but allow for measurement against container width
//with no restriction on measurer's own width (fixed)
$measurer.css({'position': 'fixed', 'top': '100%'}).appendTo("body");

//Iterate through each "word" derived from splitting on any space.
$p.text().split(/\s/).forEach(function (elem) {
    //Start forming line text.  Don't forget word spacing
    $line.text($line.text() + elem + ' ');

    //Enough words to make the line width longer than the p width.
    //This indicates the end of "line."
    if ($line.width() > $p.width()) {
        //Remove the last word.
        $line.text(function (_, text) {
            return text.slice(0, text.lastIndexOf(elem));
        });

        //Keep the currently formed line to add back later
        $line.appendTo($keeper);

        //Create a new line for measuring
        $line = $("<span>");
        $line.text(' ' + elem).appendTo($measurer);
    }
});
//Append any leftover words not big enough to form a whole line
$keeper.append($measurer.html());
//Add back content
$p.html($keeper.html());
//cleanup
$keeper.remove();
$measurer.remove();

http://jsfiddle.net/6Cx3h/2/

如果容器的宽度取决于窗口,您也可以在窗口调整大小时执行此操作.

(你可以看到我在http://jsfiddle.net/6Cx3h使用高度而不是宽度的尝试)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐