突出显示鼠标上的单行 [英] Highlight single line on mouse over

查看:131
本文介绍了突出显示鼠标上的单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当鼠标悬停在多行段落中时(该行中的任何字词),我想更改单行可以使用JQuery / JS实现?

I want to change the background color of a single line in a multi-line paragraph when the mouse is over that line (over any word in that line) - can this be achieved using JQuery/JS?

如果是,如何?

编辑
,我想让任何一行突出显示一旦鼠标在它上面。

脚本将必须动态隔离光标所在的行,并应用一个临时样式

To clarify, I want any line to be highlighted once the mouse is over it.
The script will have to dynamically isolate the line that the cursor is over and apply a temporary style to it while the mouse is over it.

编辑2:

图片说明 -

Edit 2:
A picture for illustration -

推荐答案

这是一个艰苦的战斗,但我想出了一个办法,没有任何对容器上的样式要求(包括其字体,对齐等)。

It was a hard fought battle, but I came up with a way to do this without any requirements for styles on the container at all (including its font, alignment, etc.).

这不是一个完美的解决方案,但希望它可以为您的目的。

This is not a perfect solution, but hopefully it works for your purposes.

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/

您也可以在窗口调整大小时,如果容器的宽度为window-

You can also do this on window resize in case the container's width is window-dependent.

(您可以在使用height(而不是width)查看我的尝试) http://jsfiddle.net/6Cx3h

这篇关于突出显示鼠标上的单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆