简体   繁体   English

需要jQuery改变DIV中的我的背景图像

[英]Need Jquery chaning My Background image in a DIV

I`m starting level in jquery , but i have the concept of my idea , i have a #SlidShow div , all i need to change the css property ( background-image ) every 3 second , i have i think 4 image , so my concept is (( Make New Array with images link )) and change the .css( background-image ) of this div with this array every 3s .. 我是jquery的起点,但是我有我的想法的概念,我有#SlidShow div,我需要每3秒更改一次css属性(background-image),我想有4张图片,所以我概念是((使用图像创建新数组链接))并每3s用此数组更改此div的.css(background-image)..

i hope that my concept be right :) , can any one help me with that 我希望我的概念是正确的:),任何人都可以帮我

#('SlideShow').css('background-image', (Array /* Cant handle it */));
var array = ['url(a.png)', 'url(b.png)', 'url(c.png)', 'url(d.png)'];

var i = 0;
function setBackgroundImage() {
    $('#SlideShow').css('background-image', array[i]);
    i = i % array.length;
}
setBackgroundImage();
setInterval(setBackgroundImage, 3000);

You already got your answer. 您已经得到了答案。 Just wanted to add that jQuery is a bit overkill if this is all you want to do, but it's probably not. 只是想补充一点,如果这只是您想做的事情,那么jQuery有点矫kill过正,但事实并非如此。

Here is a pure javascript solution: 这是一个纯JavaScript解决方案:

http://jsfiddle.net/2BQV5/2/ http://jsfiddle.net/2BQV5/2/

var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];

window.onload = function ()
{
    index = 0;
    var c = document.getElementById('cat');
    setInterval(function() {
        if(index > arr.length-1) {index = 0}
        c.style.backgroundImage='url(' + arr[index++] + ')';
    }, 3000);
}

Have fun! 玩得开心!

Edit 编辑

However for the second request in the comments, to have to pictures fade, jQuery is probably more suited. 但是,对于注释中的第二个请求,要使图片褪色,jQuery可能更适合。

Here is one way to achieve the fading effect: 这是一种实现淡入淡出效果的方法:

http://jsfiddle.net/8jWT5/ http://jsfiddle.net/8jWT5/

var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];

$(document).ready(function() {
    var c = $('#cat');
    fade = document.createElement('div');
    $(fade).attr('style','position: absolute; width:' + c.width() + 'px; height:' + c.height() + 'px;').attr('id','fade').hide();
    c.append(fade);

    var index = 0;
    setInterval(function () {
        $('#fade').css('background-image', 'url(' + arr[index] + ')').fadeIn(500,function() {
            c.css('background-image', 'url(' + arr[index++] + ')');        
            if(index > arr.length-1) {index = 0}
            $(this).hide();
        });
    }, 3000);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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