开发者

jQuery animate to transparent

开发者 https://www.devze.com 2023-01-15 06:53 出处:网络
$(\".block li\").hover( function(){ $(thi开发者_开发知识库s).animate({backgroundColor: \"#000\"});
$(".block li").hover(
    function(){
        $(thi开发者_开发知识库s).animate({backgroundColor: "#000"});
    },
    function(){
        $(this).animate({backgroundColor: "#fff"});
    }
);

Need to change #fff to no color. Animation should occur from #000 to transparent.

Any solution?


You could use rgba(...) (see browser support here).

var elem = $('#foo')[0];

$({
    r: 0,
    g: 0,
    b: 0,
    a: 1
}).animate({
    a: 0
}, {
    step: function() {
        elem.style.backgroundColor =
            'rgba(' +
                ~~this.r + ',' + ~~this.g + ',' + ~~this.b + ',' +
                ~~(this.a*100)/100 +
            ')';
    },
    duration: 1000
});​

~~ is to floor values, otherwise you'll end up with stuff like rgba(0.1029302....


Instead of changing background color, remove that attribute!

The code is as simple as:

$("li").hover(
    function(){
        $(this).toggleClass('hover', 1000);
    },
    function(){
        $(this).toggleClass('hover', 2000);
    }
);

Example: http://jsfiddle.net/rdWTE/

For it to work, you need jQuery and jQuery UI. Does exactly what you wanted (except the colors)!

Those numbers in jQuery script stand for animation duration in milliseconds.

EDIT:

Uhm... Found out that toggleClass can bug from time to time. Better to use addClass on hover, and removeClass on mouse out.


Edit: I have tested this and it works.

Create two classes. One with background: #000 and one with background: transparent;

Animate the toggleClass or removeClass for the #000 background class.

example:

jQuery('.block li').hover(function() {
  $(this).toggleClass('blackClass', 'fast' );
}

CSS:

.blackClass { background: #000; }


This might work. It prepends a new div with a background color onMouseOver, then it fades out and removes the div onMouseOut.

Example.

Example with list items over an image.

Good luck, hope this helps.


Why not use the opacity CSS3 tag?


I think you need to use the color plugin.


This may require some change to your HTML and CSS (which could be effected by script if you don't have direct HTML/CSS control).

I would split each '.block li' element into two elements: one that will be the background element that can be animated with $.fadeTo(), and another element laid over the top that will contain your foreground content and on which you can call $.hover() with your handlers.


$(".block li").hover( function(){ $(this).animate({backgroundColor: "#000"}); }, function(){ $(this).animate({backgroundColor: $(this).parent().css("backgroundColor") }); } );


I got a solution to this issue from this link

$('#test').animate({

backgroundColor: "#DFC21D",

}, 1000, function() {

$('#test').css("backgroundColor","transparent");

});
0

精彩评论

暂无评论...
验证码 换一张
取 消