javascript - 隐藏/显示图像 jQuery

标签 javascript jquery html show-hide

好吧。 我想要做的是在顶部创建一些按钮,这将隐藏/显示元素。
如果用户按“350x150”,它将隐藏除“350x150”图像之外的所有图像。

1). User presses "350x150"
2). All images hide except for the two "350x150"

我尝试使用一些 jQuery 来隐藏图像,但它不起作用。
我该怎么做?

What I want it to look like 图像是这样完成的:

                <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/

相关文章:

javascript - 如何将文本框弹出窗口(Jquery 工具提示或类似的)添加到 Canvas 中的 Fabric JS 图像?

javascript - jQuery,单击其可单击容器内的元素 - 如何覆盖

javascript - 过滤多个对象数组,其中基于 contractNumber 在 javascript 中找到它的平均值

javascript - Bug 动画 JavaScript

javascript - 定位元素失败

javascript - 用于多个选择选项下拉列表的本地存储

javascript - 为什么替换构造函数的原型(prototype)没有反射(reflect)在对象中?

JavaScript 使用 EventListener 和 jQuery 添加和删除 <tr>

javascript - 如何将工具栏按钮放置在标题标签的右侧?

jquery - KnockoutJS 模板 : error 'Your version of jQuery.tmpl is too old - jQuery.tmpl 1.0.0pre'