How can I highlight the line of text that is closest to the mouse?

后端 未结 3 1595
轮回少年
轮回少年 2020-11-30 05:01

I have a long text and I\'d like to offer the user a reading help: The current line should be highlighted. To make it easier, I\'ll just use the Y coordinate of the mouse (t

3条回答
  •  -上瘾入骨i
    2020-11-30 06:03

    The best approach that comes to mind is splitting each line into a or

    element that has a :hover CSS class with the "highlight" setting set:

    span.line:hover { background-color: lightblue; }
    

    That would be the least expensive solution, as the browser is going to take care of all the highlighting itself. If you want fancy effects, you can still achieve that by adding mouseover and mouseout events to every line.

    The tough part, of course, is splitting the content into lines at the browser's line break. You need to do that dynamically so the lines actually reflect the positions at which the browser breaks the text.

    Maybe the accepted answer to this question is a step into the right direction:

    Getting a specific line using jQuery

    How it works:

    It goes through the entire element (actually, a clone of the element) inserting a element within each word. The span's top-offset is cached - when this offset changes we can assume we're on a new line.

提交回复
热议问题