Highlight lines of text on mouseover [duplicate]

2019-03-21 12:12发布

This question already has an answer here:

I'm currently working on a website which will feature a bunch of stories for people to read (basically a blog). I want to make them as easy to read as possible and I figured it would be useful to 'highlight' lines of text with the cursor. Kinda like following the lines of text with your finger when reading a book.

I stumbled upon this answer, however I can't seem to get it to work for my page. It's also a pretty old answer so maybe there's an improved version of this?

If anyone could help me out I'd be forever grateful!

2条回答
手持菜刀,她持情操
2楼-- · 2019-03-21 12:16

Wrote some jQuery code that, atleast to me, both looks and works better than the code in the post that you are referring to. Hope it fits your needs :)

There's also a live demo up at http://jsfiddle.net/gFTrS/2/

HTML

<div class="textWrapper">
    <div class="highlight"></div>
    <p>Your text goes here</p>
</div>

CSS

.textWrapper
{
    position: relative;
    width: 600px;
    padding: 0px 10px;
    margin: 0 auto;
    cursor: default;
}

.textWrapper p
{
    font: normal 12px Arial;
    color: #000000;
    line-height: 18px;
    padding: 0;
    margin: 0;
}

.highlight
{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 18px;
    background: yellow;
    z-index: -1;
    display: none;
}

jQuery

$(document).ready(function()
{
    var lineHeight = 18;

    $('.textWrapper').hover(function()
    {
        $('.highlight', this).show();

        $(this).mousemove(function(e)
        {
            var relativePos = e.pageY - this.offsetTop;
            var textRow = (Math.ceil(relativePos / lineHeight) * lineHeight) - lineHeight;
            if (textRow => 0)
            {
                $('.highlight', this).css('top', textRow + 'px');
            }
        });
    }, function()
    {
        $('.highlight', this).hide();
    });
});
查看更多
戒情不戒烟
3楼-- · 2019-03-21 12:21

Most of the answers and suggestions in the older post on SO you reffered to try to manipulate the DOM by adding spans or divs for each line. But that's actually not a waterproof approach since it is not cross- browser compatble, especially not with mobile browsers. You should use a dynamically jquery controlled div that jumps behind the lines. The div should be dynamically be positioned with a jquery function triggered on mousemove calculating the div jumping on line-height depending on mouse cursor position

查看更多
登录 后发表回答