Highlight changes?

只愿长相守 提交于 2020-01-02 15:49:23

问题


HTML:

<html>
<body>
    <textarea>Original Text</textarea>
    <button>Replace</button>
</body>
</html>

jQuery:

$(function() {
 $('button').click(function () {
     $('body').html($('body').html().replace('Original','New'));
 });
});

http://jsfiddle.net/r7MgY/

Can I highlight changes somehow with a fading yellow background maybe?


回答1:


As Sarfraz says, use the jQuery color plugin. Usage is the same as animate method in jQuery. The plugin overrides the animation methods for these properties: 'backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'.

jQuery animate method usage and info can be found here: http://api.jquery.com/animate/

Also, if you want to replace something in the HTML it's better to get the wrapper tag of the tag that contains what you want invoke the replace method on instead of search through the entire body as a string. Normally you'd use:

$('#idOfMyWrapperTag').html().replace('this', 'that')

But since you are using a textarea you can get it's value with this:

$('textarea').val().replace('this', 'that');

..fredrik




回答2:


Because its a textarea, you cant inject any html directly into the content. You would have to overlay an absolute positioned element containing a red squiggle or similar - which becomes a bit of a nightmare when working out the exact location of the text.

If possible, ditch the textarea and just use an editable div or similar.




回答3:


Can I highlight changes somehow with a fading yellow background maybe?

You will have to use the jquery color plugin to fade the background color.




回答4:


You might be able to workaround it with

$(function() {
  $('button').click(function () {
     $('body').html($('body').html().replace(/Original/g,'<span class="fade" style="opacity: 0; background-color: yellow;">New</span>'));
     $('.fade').animate({
        'opacity': 1
     }, 1000, function(){
        $(this).contents().unwrap();
     });
  });
});



回答5:


If you don't want to include yet another plugin, you can simply use a little jQuery code to accomplish a fading overlay:

jQuery.fn.highlight = function() {
   $(this).each(function() {
        var el = $(this);
        el.before("<div/>")
        el.prev()
            .width(el.width())
            .height(el.height())
            .css({
                "position": "absolute",
                "background-color": "#ffff99",
                "opacity": ".9"   
            })
            .fadeOut(500);
    });
}

$("#target").highlight();

Credit goes to this answer: https://stackoverflow.com/a/11589350/1145177



来源:https://stackoverflow.com/questions/2863641/highlight-changes

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