【问题标题】:Highlight lines of text on mouseover [duplicate]鼠标悬停时突出显示文本行[重复]
【发布时间】:2012-08-13 05:55:57
【问题描述】:

我目前正在开发一个网站,该网站将提供一系列供人们阅读的故事(基本上是一个博客)。我想让它们尽可能易于阅读,并且我认为用光标“突出显示”文本行会很有用。有点像看书时用手指跟随文本行。

我偶然发现了this answer,但我似乎无法让它在我的页面上工作。这也是一个相当老的答案,所以也许有一个改进的版本?

如果有人能帮助我,我将永远感激不尽!

【问题讨论】:

  • jsbin 上的示例看起来非常高效。您能否发布您的代码,以便我们了解它为什么不起作用?
  • 更新:已添加。它应该只适用于网站左侧的文章(而不是滑块)。 s-hosting.nl/creepypastaindex

标签: javascript jquery html css highlight


【解决方案1】:

编写了一些 jQuery 代码,至少在我看来,它们看起来和工作起来都比您所指的帖子中的代码更好。希望它符合您的需求:)

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

【讨论】:

  • 我会试试这个,如果成功了再报告
  • 你去!这就是我的意思(未经测试)。快速编写脚本!
  • 好的,我刚刚尝试添加它,但它似乎不起作用(我很可能做错了什么)你可以在这里看到它:s-hosting.nl/creepypastaindex(左下角的帖子)
  • @Fred-ii- 啊,没看到^^
  • @Fred-ii- 不会出现在记事本中,但当我右键单击它时会出现在“在 Google 中搜索...”
【解决方案2】:

关于 SO 的较早帖子中的大多数答案和建议都是您尝试通过为每行添加跨度或 div 来操作 DOM。但这实际上不是一种防水的方法,因为它不兼容跨浏览器,尤其是与移动浏览器不兼容。您应该使用动态 jquery 控制的 div 来跳到行后面。 div 应该使用在 mousemove 上触发的 jquery 函数动态定位,根据鼠标光标位置计算 div 在 line-height 上的跳跃

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多