change background image onClick

自古美人都是妖i 提交于 2019-12-23 06:10:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!