问题
How can I do to change background image onClick with jquery or java script?
For Example: I have Six(6) images and I want change to NEXT background image when i click on ">" (next arrow) and change to previous background image when I click on "<" (back arrow).
I'm developing this website with responsive html5 and css3.
回答1:
You can list your images in an array and then change the background-image css attribute on click:
var images = ['url("image1.png")', ...], curIndex = 0;
// Left arrow selector
$('.left-arrow').click(function () {
if (curIndex > 0) {
// Container selector
$('#container').css('background-image', images[--curIndex]);
}
});
// Right arrow selector
$('.right-arrow').click(function () {
if (curIndex < images.length - 1) {
// Container selector
$('#container').css('background-image', images[++curIndex]);
}
});
HTML Would be:
<div id="container">
<img class="left-arrow" src="image-path" />
<img class="right-arrow" src="image-path" />
<div>
回答2:
If you don't want to use any other 3rd party libraries:
$("#YourElementId").css("background-image", "url('http://url.com/image1.jpg')");
回答3:
$("#id").on("click", function () {
$(this).css("background-image", "url(/url/to/background/image.jpg)");
});
来源:https://stackoverflow.com/questions/13087684/change-background-image-onclick