javascript - 突出显示鼠标悬停的单行

标签 javascript jquery html css

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

如果是,怎么做到的?

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

编辑 2:
一张图说明 -
enter image description here

最佳答案

这是一场艰苦的战斗,但我想出了一种方法来做到这一点,完全不需要容器上的样式(包括其字体、对齐方式等)。

这不是一个完美的解决方案,但希望它能满足您的需求。

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 处看到我使用高度而不是宽度的尝试)

关于javascript - 突出显示鼠标悬停的单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148128/

相关文章:

javascript - Angular 有一个元素不在 Angular 模板中时显示

javascript - 从具有相同类的不同 HTML 元素中获取值

html - 给 li 分配宽度

javascript - 使用 bxSlider 切换类

javascript - 取消选中复选框时删除附加的 div

jquery - 我们可以在 2013 年修复 Youtube 拒绝 'toString' 问题吗?

java - 如何使用 OkHttp - Android 将 html 源代码获取到字符串

javascript - 如何将列表中选定的数据添加到多个选择框?

javascript - jQuery 使用 for 循环触发事件 n 次

javascript - jQuery如何在preventDefault()之后启用标签