0

I am using Jquery to highlight a span of text when a trigger is clicked.

I am looking for a way to have the text highlighted from left to right, instead of all in one go, to give a "real" feel - so that it looks like it's being highlighted by hand.

I can't find any documentation about this online.... Any ideas?

Here is the code:

(HTML)

The Law of Universal Gravitation is based on the observed fact 
that all masses attract all other masses. The force of 
<span id="to_highlight">attraction decreases as the distance 
between the masses increases.</span>

(JQuery)

if (count==4) {
  $('#to_highlight').css("background-color","#e8c5e8");
};
4

2 回答 2

1

您可以使用此处说明的方法来完成您要查找的内容。

设置 abackground: linear-gradient(to right, yellow 50%, white 50%);然后使用background-position: left bottom;background-position: right bottom;组合 withtransition:all 3s ease;以获得从左到右的效果。

这是一个来自 gar_onn 的答案的 JSFiddle(第一行的链接):http:
//jsfiddle.net/23zea/

希望这就是你要找的。

于 2013-06-23T15:10:11.527 回答
1

不幸的是,没有简单的方法可以做到这一点。JQuery 动画依赖于有一个元素来制作动画。由于我假设您可能不希望文本本身被动画化,因此您必须为不同的元素设置动画。

我制作了一种方法,您可以调用该方法来为突出显示设置动画。它将动态创建一个新元素,该元素将被动画化,然后丢弃该元素并用一个将使用 css 突出显示该元素的类替换它。

HTML

<button id="highlight_trigger">Highlight</button>
<span id="to_highlight">This text is what I want to highlight</span>

JS

$('#highlight_trigger').on('click', function() {
    var toHighlight = $('#to_highlight');
    if(toHighlight.hasClass('highlighted')) {
        highlightAnimation(toHighlight, false, 500);
    } else {
        highlightAnimation(toHighlight, true, 500);
    }
});

function highlightAnimation($elem, show, duration) {
    var startPos;
    var endPos;
    if(show) {
        startPos = '100%';
        endPos = '0%';
    } else {
        startPos = '0%';
        endPos = '100%';
        $elem.removeClass('highlighted');
    }
    var highlight = $('<div />').addClass('highlight_box').css('right', startPos);
    $elem.append(highlight);
    highlight.animate({right: endPos}, duration, function() {
        highlight.remove();
        if(show) {
            $elem.addClass('highlighted');
        }
    });
}

CSS

#to_highlight {
    display: inline-block;
    position: relative;
}

#to_highlight.highlighted, .highlight_box {
    background-color: yellow;
}

.highlight_box {
    display: block;
    position: absolute;
    top: 0; bottom: 0; left: 0;
    z-index: -1;
}
于 2013-06-23T15:10:47.800 回答