gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:36:28 27 4
gpt4 key购买 nike

我想更改多行段落中单行的背景颜色,当鼠标悬停在该行上时(悬停在该行中的任何单词上)-这可以使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com