[英]change background image onClick
How can I do to change background image onClick with jquery or java script? 如何使用jquery或java脚本更改背景图片onClick?
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). 例如:我有六(6)张图像,我想在单击“>”(下一个箭头)时更改为下一个背景图像,并在单击“ <”(后退箭头)时更改为上一个背景图像。
I'm developing this website with responsive html5 and css3. 我正在使用响应式html5和CSS3开发该网站。
You can list your images in an array and then change the background-image css attribute on click: 您可以在数组中列出图像,然后在单击时更改background-image css属性:
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: HTML将是:
<div id="container">
<img class="left-arrow" src="image-path" />
<img class="right-arrow" src="image-path" />
<div>
如果您不想使用任何其他第三方库:
$("#YourElementId").css("background-image", "url('http://url.com/image1.jpg')");
$("#id").on("click", function () {
$(this).css("background-image", "url(/url/to/background/image.jpg)");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.