如何在2张图像之间切换
我试图使用此代码在播放和暂停按钮之间切换,但它似乎没有工作。 如何在单击时在两个图像之间切换
http://jsfiddle.net/aFzG9/1/
$("#infoToggler").click(function() { if($(this).html() == "") { $(this).html(""); } else { $(this).html(""); } });
谢谢
一种不同的可能更简单的方法来处理它:
$("#infoToggler").click(function() { $(this).find('img').toggle(); });
纯HTML / CSS
http://jsbin.com/jQuery_Toggle/5/edit
label.tog > input{ display:none; /* hide the checkbox */ } label.tog > span{ display:inline-block; /* use also vertical-align:middle; if needed */ width:16px; height:16px; background: url("http://sofzh.miximages.com/jquery/play.png"); } label.tog > input:checked + span{ background-image: url("http://sofzh.miximages.com/jquery/pause.png"); }
切换内跨的图像
有用的原因是服务器没有新的请求加载图像:
http://jsbin.com/jQuery_Toggle/4/edit
$(".tog").click(function(){ $('img',this).toggle(); });
或者,假设我们有这个HTML和.tog
图像选择器:
使用Array.prototype.reverse()
http://jsbin.com/jQuery_Toggle/1/edit
var togSrc = [ "http://sofzh.miximages.com/jquery/play.png", "http://sofzh.miximages.com/jquery/pause.png" ]; $(".tog").click(function() { this.src = togSrc.reverse()[0]; });
使用当前的src
值和String.prototype.match()
如果您不知道初始状态(播放?暂停?),这很有用
http://jsbin.com/jQuery_Toggle/3/edit
var togSrc = [ "http://sofzh.miximages.com/jquery/play.png", "http://sofzh.miximages.com/jquery/pause.png" ]; $(".tog").click(function() { this.src = togSrc[ this.src.match('play') ? 1 : 0 ]; });
注意:对于最后两个示例,您需要预先加载图像,以防止浏览器从服务器加载新图像的时间间隔。
您可以使用.toggle()
函数。 我已经更新了你的小提琴。 此外,您还没有在图片代码中正确转义引号。
$("#infoToggler").toggle(function() { $(this).html(''); }, function() { $(this).html(''); });
$(document).ready(function(){ var src1 = "http://sofzh.miximages.com/jquery/play.png"; var src2 = "http://maraa.in/wp-content/uploads/2011/09/pause-in-times-of-conflict.png"; $("#infoToggler").click(function(){ var src = $('#infoToggler img').attr('src'); if(src == src1){$('#infoToggler img').attr('src',src2);} else{$('#infoToggler img').attr('src',src1);} });
})
它工作,我检查..