jQuery backgroundColor animation

2019-04-08 05:00发布

I have a DIV with a link and a SPAN.

When clicking the link, it renders a list of items by using AJAX. When an item is clicked, the content of the SPAN is changed.

I want to highlight this change, by setting the background-color of the DIV to green, and animating it back to white using jQuery.

  var originalColor = elementToUpdate.parentNode.style.backgroundColor;
  elementToUpdate.style.backgroundColor = 'green'; //lastSender.style.color;
  jQuery(elementToUpdate.id).animate({ backgroundColor: '#ffffff' }, 1000);

The background of the SPAN is changed to green on the 2nd line, but the 3rd line doesn't do anything. No errors, or changes what so ever...

Any ideas?


Edit: As noted by Ted Naleid in a comment below:

Also note that you have to have the color animations plugin installed for this to work (http://plugins.jquery.com/project/color), if you don't have it installed, jQuery can't animate colors, only numeric properties (at least as of 1.3.1).

1条回答
我想做一个坏孩纸
2楼-- · 2019-04-08 05:01

You don't need the .id if you already have the element. Hand it directly to jQuery:

jQuery(elementToUpdate).animate({ backgroundColor: '#ffffff' }, 1000);

You don't get an error because elementToUpdate.id is a string, which jQuery (probably) interprets as a selector. It just happens to be a selector that doesn't select anything.

Alternatively, you can say this to make it a valid selector:

jQuery('#' + elementToUpdate.id).animate({ backgroundColor: '#ffffff' }, 1000);

But I think the first form is preferable since you already have the element itself.

查看更多
登录 后发表回答