简体   繁体   中英

how to change div background-color with fadeIn/Out?

如何使用淡入/淡出更改div背景颜色,我只想淡化背景颜色,而不是背景图片,请给我一些有用的代码或解决方案

Although only supported by modern browsers you might also consider using CSS transitions to achieve the same effect

HTML

<div class='foobar'></div>

CSS

.foobar {
    /* transition properties */
    transition: background-color 2s;
    -moz-transition: background-color 2s;
    -webkit-transition: background-color 2s;
    -o-transition: background-color 2s;

    /* basic styling & initial background-color */
    background-color:maroon;
    width:100px;
    height:100px;
}

/* Change background color on mouse over */
.foobar:hover {
    background-color:blue;
}

Working example here, http://jsfiddle.net/eRW57/14/

You can't fade just the background (color or otherwise) of an element using jQuery's fadeIn/fadeOut.

What you can do is place an additional layer (DIV, etc) with your background color and fade in/out on that.

Instead of something like this:

<div id="my-background"></div>

Use this structure:

<div id="container">
  <div id="my-background"></div>
</div>

CSS

#container
{
 position:relative;
 width:200px;
 height:100px;
 background-image:url(my-background-image.jpg);
}
#my-background
{
 height:100%;
 width:100%;
 background-color:blue;
 position:absolute;
 z-index:99;
}

Then use jQuery's fadeIn/fadeOut methods

JS

jQuery("#my-background").fadeOut();
<script>
$(document).ready(function(){
  $("p").toggle(function(){
    $("body").css("background-color","green");},
    function(){
    $("body").css("background-color","red");},
    function(){
    $("body").css("background-color","yellow");}
  );
});
</script>

try it.. that should work fine

with this you can fadeout all div's with id #my-background

var $div = $('#my-background');
  $div.each(function blank(){
  $(this).animate({'backgroundColor': '#fff'},2000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM