突出显示<div> </div>中单行文本的效果

时间:2014-08-27 14:43:04

标签: javascript jquery html css highlighting

我想重新创建this fiddle

中显示的效果

根据StackOverflow规则,如果我链接到jsfiddle.net,我显然必须提供一些代码,所以这里是该链接的主要功能。虽然要看到效果,你显然必须遵循链接。

$(document).ready(function() {
  $(".textWrapper").hover(function() {
    $(".highlight", this).show();
    $(this).mousemove(function(e) {
      var relativePos = e.pageY - this.offsetTop;
      var textRow = (Math.ceil(relativePos / 18) * 18) - 18;
      if (textRow >= 0) { $(".highlight", this).css("top", textRow + "px"); }
    });
  }, function() {
    $(".highlight", this).hide();
  });
});

不是以黄色突出显示文本,而是更喜欢更改文本本身的颜色。

我希望文字为浅灰色,并在突出显示时变暗,以使该线成为焦点。这似乎比简单地更改CSS要困难得多,因为实际的文本属性不会改变。

我如何做到这一点?

2 个答案:

答案 0 :(得分:4)

看看:

http://jsfiddle.net/5nxr6my4/

使用相同的原理,我创建了2个白色不透明div s #highTop#highBot,以便在鼠标指针悬停在其上时覆盖文本。他们的heighttop属性会调整为指针位置,因此基础黑色文本显示为灰色,但鼠标指针指向的行除外:

$(document).ready(function() {
    $('#highTop').css('height', $('.textWrapper').height()).show();

    $('.textWrapper').hover(function() {   
        $('#highBot').show();
        $(this).mousemove(function(e) {
           var relativePos = e.pageY - this.offsetTop;
           var textRow = (Math.ceil(relativePos / 18) * 18) - 18;
           if (textRow >= 0) { 
              // change height of #hightTop to make it cover upper part of text
              $('#highTop').css('height', textRow + 'px'); 
              // change position and height of #highBot to make it cover lower part of text
              $('#highBot').css('height', $('.textWrapper').height() - 18 - textRow + "px")
                           .css('top', textRow + 18 + 'px');
           }
        });
    }, function() {
        // when the pointer goes out of the text, hide #highBot and make #highTop cover entire text
        $('#highTop').css('height', $('.textWrapper').height() + 'px');
        $('#highBot').hide();
    });
});

答案 1 :(得分:1)

我做了一些研究,似乎唯一可行的方法是将每一行放在一个单独的HTML标记中。

您无法按照自己喜欢的方式进行操作的原因是,.highlight div不包含文本本身,因此您只能应用叠加而不是编辑下方文本。

查看仅显示某些文字行的http://jsbin.com/ukaqu3/91可能会有所帮助。