Highlight lines of text on mouseover [duplicate]

倖福魔咒の 提交于 2020-01-01 03:29:09

问题


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!


回答1:


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();
    });
});



回答2:


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



来源:https://stackoverflow.com/questions/11994696/highlight-lines-of-text-on-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!