好吧。
我想要做的是在顶部创建一些按钮,这将隐藏/显示元素。
如果用户按“350x150”,它将隐藏除“350x150”图像之外的所有图像。
1). User presses "350x150"
2). All images hide except for the two "350x150"
我尝试使用一些 jQuery 来隐藏图像,但它不起作用。
我该怎么做?
<div class="Collage">
<img class="boom" src="http://placehold.it/1000x150">
<img class="ei" src="http://placehold.it/150x150">
<img class="boom" src="http://placehold.it/200x150">
<img class="ei" src="http://placehold.it/200x350">
<img class="350x150" src="http://placehold.it/350x150">
<img class="350x150" src="http://placehold.it/350x150">
<img class="boom" src="http://placehold.it/500x150">
<img class="ei" src="http://placehold.it/50x200">
<img class="boom" src="http://placehold.it/350x200">
<img class="ei" src="http://placehold.it/600x200">
</div>
最佳答案
您可以将“filter-btn”添加到您的过滤器 btns 类中,然后它们的 id 可以与您要显示的类相同,例如 id="350x150"或 id="boom"或 id= “ei”...我想你明白了:)
$(".filter-btn").click(function(){
var filterVal = "." + $(this).attr("id");
$(".Collage img").show();
$(".Collage img").not(filterVal).hide();
});
或者您可以先隐藏所有内容,然后显示您需要的内容:
$(".filter-btn").click(function(){
var filterVal = "." + $(this).attr("id");
$(".Collage img").hide();
$(".Collage img").filter(filterVal).show();
});
编辑或更好地缓存您的元素:
var $collageImages = $(".Collage").find("img"); // cache your elements!
$("#filter350x150").click(function(){
$collageImages.hide(); // Hide all
$(".350x150").show(); // Show desired ones
});
// other buttons here...
或者使用更通用的代码:
var $collageImages = $(".Collage").find("img"); // cache your elements!
$("[id^=filter]").click(function(){ // any button which ID starts with "filter"
var class = this.id.split("filter")[1]; // get the filterXYZ suffix
$collageImages.hide(); // Hide all
$collageImages.is("."+ class ).show() // Show desired ones
});
关于javascript - 隐藏/显示图像 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32359135/