如果元素可见,则对另一个元素执行某些操作。 jQuery
我有多个像这样的容器
<div class="container">
<span>
<!-- Inside the span is either text or img -->
</span>
</div>
目标是仅当它包含图像时才在“.container span”周围有边框。
我尝试过这样的事情..但它不起作用
if( $(this).find('.container span img').is(":visible") ){ $(".container span").css({'border':'10px'}); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
visible
是一个伪选择器,所以它是你也可以像这样使用它
编辑
嘿,等等,你是说它可能不包含图像根本吗?在这种情况下,您不想检查可见性,而是检查类似的内容
(当然,如果可能有图像,并且它们可能被隐藏,那么您想要检查
img:visible
的长度)编辑 2
现在您已经可以检查是否存在可见图像了。其余的取决于您的实施。我假设通过使用
$(this)
将会有某种类型的 DOM 节点可供搜索,对于每个值只有一个.container
这个
。如果情况并非如此 - 如果您想一次性查看 DOM 的所有 - 您可以执行以下操作:
上面,您说的是“对于跨度内的所有可见图像”在
.container
中,为其父跨度添加边框另一种方法是这样的:
visible
is a pseudo selector so it'sYou can also use it like so
EDIT
Hey, wait, are you saying that it might not contain an image at all? In that case, you don't want to be checking for visibility, but rather something like
(of course, if there might be images, and they might be hidden, you want to check the length of
img:visible
)EDIT 2
Now you've got a working check as to whether or not there is a visible image. The rest depends on your implementation. I assumed from the use of
$(this)
that there will be a DOM node of some kind to search within, that'll only have one.container
for each value ofthis
.If that's not the case - if you want to look at all of the DOM in one go - you could go about something like this:
Above, you're saying that "for all visible images inside a span inside a
.container
, add a border to their parent spans.Another way of doing it would be something like this:
你有两个问题。首先,你的css是错误的。你告诉它给它一个 10px 的边框,什么都没有。您需要指定边框的种类以及可能的颜色。
其次,
.is("visible")
应该是.is(":visible")
查看 jsfiddle.net
(我必须删除
this
选择器,但您可以将现有代码修改为上述内容。)You have two problems. First, your css is wrong. Your telling it to give it a 10px border of nothing. You need to specify what kind of border and probably the color.
Second,
.is("visible")
should be.is(":visible")
Check out the working code on jsfiddle.net
(I had to remove the
this
selector but you can modify your existing code to the above.)http://jsfiddle.net/VMAJ7/1/
http://jsfiddle.net/VMAJ7/1/
您拥有
span
. 是否有原因?您可以将边框直接应用于图像,而不需要跨度标签,特别是当您动态加载图像并且图像具有不同尺寸时。然后,您必须确保调整跨度标签的大小以匹配图像的宽度和高度。您可以通过删除span
标签来简化事情,否则如果所有图像都具有相同的尺寸,则需要指定跨度宽度和高度。另外,不要忘记指定边框属性,例如样式和颜色。检查工作示例 http://jsfiddle.net/GnXv4/6/
Is there a reason why you have the
span
. You can apply the border directly to the image without the need for a span tag, specially if you are loading your images dynamically and your images have different dimensions. You then have to ensure your span tag is resized to match your image width and height. You can simplify things by getting rid of thespan
tag, else if all your images have same dimensions, you need to specify your span width and height. Also don't forget to specify your border properties such as style and color.Check working example at http://jsfiddle.net/GnXv4/6/