我想改变单行在多行段落中的背景色,当鼠标位于该线上时(在该行中的任何单词上)--这可以使用JQuery/JS实现吗?
如果是这样的话,是怎么做的?
编辑:要澄清的是,我希望鼠标在上面突出显示任何行。
脚本必须动态地隔离光标已经结束的行,并在鼠标结束时对其应用临时样式。
编辑2:
一幅插图-
发布于 2013-03-01 01:05:11
这是一场艰苦的战斗,但我想出了一种方法来做到这一点,而对容器上的样式没有任何要求(包括字体、对齐等)。
这不是一个完美的解决方案,但希望它对您的目的有效。
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上,您可以看到我使用高度而不是宽度的尝试)
发布于 2013-03-01 00:14:31
每一行都应该是一个标签,如果愿意,可以使用<span>
,然后使用css
(比javascript或jQuery更好)
span:hover{
background-color: #ccc;
}
发布于 2013-03-01 00:34:08
这完全取决于您的文本最初是如何格式化的。从您显示的屏幕截图来看,在我看来,文本被包装在一个强制行包装的元素中。在这种情况下,整个文本中没有真正的“新行”。如果元素的大小改变了.例如,您现在正在阅读的文本被包装在站点的约束中.
但如果我
插入我自己的行
打破,然后
跟随法
可能有用。
// extract the text
var paragraph = $("#text").text();
// split the text into lines by searching for linebreaks
var lines = paragraph.split(/\r?\n/);
// clear the original text
$("#text").text('');
$.each(lines,function(index,elem){
if (elem != ''){
// for each line, wrap it with a span and bring back the linebreak
$("#text").append('<span>'+elem+'</span><br/>');
}
});
现在你要做的就是制定一些css规则来突出显示悬停事件上的span元素-
span:hover { background:#DDD }
活生生的例子
https://stackoverflow.com/questions/15148128
复制相似问题