简体   繁体   中英

JQuery - Replacing a background-image for another on click

I would like to replace a background image with another background image on click. Eventually I would like to be able to toggle the image on and off by clicking the image.

HTML

     <div class="arrow-up" role="button"></div><div class="arrow-down" role="button"></div>

CSS

.arrow-up {
width: 15px;
height: 14px;
background-image: url("//b.thumbs.redditmedia.com/b3vXuNpkEkQVRIBnRfoVOgBmT-5X4BEnyMoP85J2QIg.png")!important;
background-position: center center;
border: none!important;
}

.arrow-down {
margin: 2px 0px 0px 0px;
width: 100%;
height: 14px;
display: block;
cursor: pointer;
background-position: center center;
background-repeat: no-repeat;
width: 15px;
margin-left: auto;
margin-right: auto;
outline: none;
}
.arrow-down {
width: 15px;
height: 14px;
background-image: url("//b.thumbs.redditmedia.com/b3vXuNpkEkQVRIBnRfoVOgBmT-5X4BEnyMoP85J2QIg.png")!important;
background-position: center center;
border: none!important;
}
.arrow-up {
margin: 2px 0px 0px 0px;
width: 100%;
height: 14px;
display: block;
cursor: pointer;
background-position: center center;
background-repeat: no-repeat;
width: 15px;
margin-left: auto;
margin-right: auto;
outline: none;
}
.arrow-down {
background-position: -30px -24px!important;
}
.arrow-down {
background-image: url(sprite-reddit.ZDiVRxCXXWg.png);
background-position: 0px -865px;
background-repeat: no-repeat;
}

.arrow-up {
background-position: 0px -24px!important;
}

JQuery

  $(document).ready(function () {
$(".arrow-up").click(function () {
    $(this).css("background-image", "http://i.imgur.com/rySpqwS.jpg");
});
});

Would I be able to toggle the image like this? Because this solution doesn't seem to function.

Jquery

$(document).ready(function () {
$(".arrow-up").click(function () {
 if  ($(this).css("background-image") ==      "//b.thumbs.redditmedia.com/b3vXuNpkEkQVRIBnRfoVOgBmT-5X4BEnyMoP85J2QIg.png")
 {
 $(this).css("background-image", "url(http://imgur.com/dpvAtIb.jpg)")
 }
 else {
  $(this).css("background-image", "url(//b.thumbs.redditmedia.com/b3vXuNpkEkQVRIBnRfoVOgBmT-5X4BEnyMoP85J2QIg.png)")
 }
 });

 });

The correct CSS value for a background-image is url(image)

$(document).ready(function () {
    $(".arrow-up").click(function () {
        $(this).css("background-image", "url(http://i.imgur.com/rySpqwS.jpg)");
    });
});

Note that javascript won't be able to set the background image, as it's set with !important in the CSS, and !important overwrites inline styles, so you won't see any change until you remove !important from your styles.
Using !important generally means you've failed miserably at something, it's not something you should use on all your styles.

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