简体   繁体   中英

Unable to alter the css 'background-image' with Jquery

I am trying to cycle through an array of pictures to make a photo-viewer on my webpage. The cycling method is working fine, but the transferring the message unto the css is not. I am wondering if there is any syntax issues within my javascript code or a concept that I am missing out on. I know that the cycling works because the alert I have is working.

var changeIt = ""
var backgroundPic = new Array(4);

backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';

var picCounter = 0;
var numberOfPics = 5;
var picTimer;

function setPic(){
    alert("hi I want this pic: " + backgroundPic[picCounter]);
    $('slider').css('background-image', url + "backgroundPic[picCounter]");

    picCounter += 1;
        if(picCounter >= numberOfPics){
        picCounter = 0;
    }

}

$(document).ready(function(){

    $('.slider').css('background-image', backgroundPic[picCounter]);

    picTimer = setInterval(setPic, 2000);

});

The issue is due to the incorrect syntax you're using when concatenating the CSS property value. Try this:

var backgroundPic = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];    
var picCounter = 0;
var picTimer;

function setPic() { 
    // note the . in the jquery object below to indicate a class selector
    $('.slider').css('background-image', 'url("' + backgroundPic[picCounter % backgroundPic.length] + '")');
    picCounter++;
}

$(document).ready(function() {
    picTimer = setInterval(setPic, 2000);
    setPic();
});

您必须像这样设置背景图片:

$('.slider').css('background-image', "url('" + backgroundPic[picCounter] + "')");

You inverted the positioning of the quotemarks on the second line of setPic .

Try: $('slider').css('background-image', 'url' + backgroundPic[picCounter]);

On your setPic function, this line

$('slider').css('background-image', url + "backgroundPic[picCounter]");

isn't missing a dot on $('.slider') ?

You'll need to include double quotes (") before and after the imageUrl like this:

$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');

This way, if the image has spaces it will still be set as a property.

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