javascript 如何在单击时切换两个图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15368733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to toggle two images onClick
提问by mkaatman
I'm making a collapsible treeView.
I made it all, I just need my +
and -
icons to toggle whenever they are clicked.
我正在制作一个可折叠的 treeView。我做到了,我只需要我的+
和-
图标在点击时切换。
I did the part when I change an icon from +
to -
, on click, with jQuery with the following code:
我做了一部分,当我更改图标从+
到-
上点击,使用jQuery用下面的代码:
$(this).attr('src','../images/expand.gif');
Problem is, I don't know how to make it go other way around, when i click on the node again :)
问题是,当我再次单击该节点时,我不知道如何让它以其他方式运行:)
回答by mkaatman
This should work:
这应该有效:
<style>
.expand{
content:url("http://site.com/expand.gif");
}
.collapse{
content:url("http://site.com/collapse.gif");
}
</style>
<img class="expand">
<script>
//onclick code
$('img.expand').toggleClass('collapse');
</script>
回答by mkaatman
Look for jquery function toggleClass :)
寻找 jquery 函数 toggleClass :)
Html:
网址:
<div id="box">
Hello :D
</div>
Jquery:
查询:
$("#box").click(function () {
$(this).toggleClass("red");
});
Css:
css:
#box {
width: 200px;
height: 200px;
background-color: blue;
}
.red {
background-color: red !important;
}
Remember that !important is realy important!!!
请记住!重要的是真的很重要!!!
Lots of ways to do this :D
有很多方法可以做到这一点:D
回答by SSH This
I wanted to do this without making classes. Inside your click event function, you could do something like this:
我想在不上课的情况下做到这一点。在您的点击事件函数中,您可以执行以下操作:
if($(this).attr('src') == '../images/collapse.gif')
$(this).attr('src', '../images/expand.gif');
else
$(this).attr('src', '../images/collapse.gif');
回答by Neophile
add plus as a default img src then define a minus-class to change the image source to minus image
添加 plus 作为默认 img src 然后定义一个减号类将图像源更改为减号图像
$("selector_for_your_link").click(function () {
$(this).toggleClass("minus-class");
});