好的,理论上这应该很简单,但我尝试过parent
,parentsUntil
,next
等多项内容,并且无法弄明白
我有几个div
,如下所示,每个都有一个隐藏和可见的图像,以及两个可见的按钮。当您将鼠标悬停在按钮上时,它应显示或隐藏显示/隐藏的图像。
<div class="quarterWidth boxShadow">
<h2>category</h2>
<img src="image.jpg" width="180" height="180" alt="xyz" class="normalPic">
<img src="other.jpg" width="180" height="180" alt="xyz" class="hoverPic">
<p class="button button180"><a class="trad" href="#">Traditional</a></p>
<p class="button button180"><a class="contemp" href="#">Contemporary</a></p>
</div>
我已成功隐藏.hoverPic
jQuery,当我将鼠标悬停在a.contemp
按钮上时,我希望隐藏.normalPic
图片,并显示.hoverPic
,当你将鼠标悬停在.trad
上时,会发生相反的情况。
你怎么用jQuery实现这个目标?这是我可怜的尝试:
$(function() {
$('.hoverPic').hide();
$('.contemp').hover(function(){
$(this).parentsUntil('.boxShadow').next('.normalPic').hide();
$(this).parentsUntil('.boxShadow').next('.hoverPic').show();
});
$('.trad').hover(function(){
$(this).parentsUntil('.boxShadow').next('.normalPic').show();
$(this).parentsUntil('.boxShadow').next('.hoverPic').hide();
});
});
答案 0 :(得分:3)
我个人会使用.closest()
找到父div
,然后将其用作上下文来查找相关图片:
$(function() {
$('.hoverPic').hide();
$('.contemp').hover(function(){
var $parent = $(this).closest("DIV");
$('.normalPic', $parent).hide();
$('.hoverPic', $parent).show();
});
$('.trad').hover(function(){
var $parent = $(this).closest("DIV");
$('.normalPic', $parent).show();
$('.hoverPic', $parent).hide();
});
});
答案 1 :(得分:2)
这应该这样做:
$('.contemp').hover(function(){
$(this)
.closest('.boxShadow')
.children('.normalPic').hide().end()
.children('.hoverPic').show();
});
$('.trad').hover(function(){
$(this)
.closest('.boxShadow')
.children('.normalPic').show().end()
.children('.hoverPic').hide();
});
这将找到与班级.boxShadow
最近的祖先,并从那里找到其子.normalPic
和.hoverPic
并更改其可见性。请注意如何使用方法链来避免一遍又一遍地搜索相同的元素。
另请注意,离开元素时将调用相同的函数。您可能只想使用hover
。
mouseenter
不重复代码,但可能不太直观:
$('.contemp, .trad').mouseenter(function(){
var is_contemp = $(this).hasClass('contemp');
$(this)
.closest('.boxShadow')
.children('.normalPic').toggle(!is_contemp).end()
.children('.hoverPic').toggle(is_contemp);
});