JQuery - 在点击时替换另一个背景图像

时间:2016-03-19 20:50:44

标签: javascript jquery html css

我想在点击时用其他背景图片替换背景图像。最后,我希望能够通过单击图像来打开和关闭图像。

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");
});
});

我可以像这样切换图像吗?因为这个解决方案似乎没有起作用。

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)")
 }
 });

 });

1 个答案:

答案 0 :(得分:2)

背景图片的正确CSS值为url(image)

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

请注意,javascript无法设置背景图片,因为它在CSS中设置为!important,而!important会覆盖内联样式,因此您赢了&# 39;在您从样式中删除!important之前,请注意任何更改 使用!important通常意味着你在某些事情上惨遭失败,这不是你应该在所有风格上使用的东西。