给予fideIn fadeOut效果更改图像src

时间:2012-10-25 12:52:45

标签: javascript jquery html

我正在处理响应式网页设计,我想将一些图片放到页面中。我尝试了一些插件,但插件的问题是它使用了width和height属性,还分配了position: absolute。所以我想用js自己改变图像的src并且它运行良好,但是我可以给它一些过渡效果吗?

Demo fiddle

我所做的是:

var i = 0;
var total = 2;
window.setInterval(function() {
    show_hide();
}, 1000);

function show_hide() {
    var img = $('.image-holder img, .image-holder2 img');
    //alert(img.length);
    if (i % 2 == 0) {
        img[0].src = 'http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png';
        img[1].src = 'http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png';
        i = 0;
    }
    else {
        img[0].src = 'http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834';
        img[1].src = 'http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834';
    }
    i++;
}

我的HTML如下:

<div  class="image-holder" >
    <img src="http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834"  />
</div>
<div  class="image-holder2" >
    <img src="http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834"  />
</div>

1 个答案:

答案 0 :(得分:1)

这是我放在一起的东西。 jsFiddle

的javascript

var img = $(".image-holder img")
var i = 0;
var count = img.length - 1;

setInterval(function() {
    showImage(i);
    i++;
    if (i > count) i = 0;
}, 2000);

function showImage(i) {
    img.eq(i - 1).animate({
        "opacity": "0"
    }, 1000);
    img.eq(i).animate({
        "opacity": "1"
    }, 1000);
}​

HTML

<div  class="image-holder" >
<img src="http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834"  />


</div>
<div  class="image-holder" >
<img src="http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png"  />
</div>​

CSS

.image-holder img{ opacity: 0;}
.image-holder { position: absolute; }