jQuery animate color change

有些话、适合烂在心里 提交于 2019-12-23 07:17:20

问题


I'm trying to animate a link color change from the current color to an other color.

$(window).load(function(){
    $('.article-preview h1 a').hover(function(){
        $(this).animate({
            color: #ffffff
        }, 1500);
    });
});

For some reason it's not working. I'm using the jQuery color plugin.


回答1:


You need to wrap the hex triplet in a string, change this:

color: #ffffff

to this:

color: "#ffffff"



回答2:


The basic problem is probably that you don't know jQuery's / JavaScript's notations,
writing #ffffff would get you SyntaxError, because SharpSign+Letters doesn't mean anything in JS.
Quick Solution: You have to pass hexa-colors as strings: color: "#ffffff"

jQuery supports a few different notations of passed-object for .css() & .animate() methods,
let me guid you through them.

Property names / Keys

(border, width,...) can be written in 3 ways:

backgroundColor    //DOM formatting
'backgroundColor'  //DOM formatting BUT - passed as a STRING
'background-color' //CSS formatting - passed as a STRING

Property values / Values

(#ffffff, 0px, none, ... ) can be written in 3 ways

0         // 'pure' number - Integer (useful when pre-calculating pixels)
20.5      //               - Float
'0'       //  number BUT passed as STRING - Integer
'20.5'    //                              - Float
'0px'     //  string
'#ffffff' //  - || -
'auto'    //  - || -

You could rougly say that everything except pixels is always passed as string
=> that means in quotes (single ' or double " ) or you could of course pass a string variable

So the safest way for beginers would probably be to always use quote notations for both - keys && values.

...

Overall

All this is actually using part of JSON - JavaScript Object Notation

All of this is described in the jQuery's .css() method documentation

Beware of

Some bugs in (older) Internet Explorers (see documentation of .css() and .animate() methods)

I did not show example of all string-passed possibilities, for example:

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

JSON object has more valid values than numbers and strings - boolean, array, object, null...



来源:https://stackoverflow.com/questions/6967188/jquery-animate-color-change

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