如果同一类,淡入/ fadout
问题描述:
我在这里的jsfiddle的设置:http://jsfiddle.net/2PmnQ/如果同一类,淡入/ fadout
我试图做的是将检查模式具有相同的类的按钮,该按钮将弹出一个功能与同类的模态。我显然是试图在一个函数内动态地完成这些动作,而不是为每个类做一个if语句。
var p = $(".popUp");
var position = p.position();
var tagLength = $("p a").width();
$(".modal").css({left: (position.left + tagLength + 10) + "px", top: position.top + "px"});
$(".popUp").hover(
function() {
$(".modal").stop().fadeIn();
}, function() {
$(".modal").stop().fadeOut();
}
);
答
我会用一个自定义的,而不是数据属性类的保存目标类:
<p class="popUp" data-modal="one"><a>popUp one here</a></p>
<p class="popUp" data-modal="two"><a>popUp two here</a></p>
<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>
这样,你不必目标筛选出触发元素类的,只需要在这您悬停功能:
$('.popUp').hover(function(){
$('.modal.'+$(this).data('modal')).fadeIn();
},function(){
$('.modal.'+$(this).data('modal')).fadeOut();
});
V2采用jQuery UI position()插件:
<!-- i switched the popup classes to the `a` here so it works in the fiddle -->
<p><a class="popUp" data-modal="one">popUp one here</a></p>
<p><a class="popUp" data-modal="two">popUp two here</a></p>
<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>
JS:
$('.popUp').hover(function(){
$('.modal.'+$(this).data('modal'))
// reset positions otherwise it doesn't work correctly after the first time. don't know why :(
// looks like this problem: http://forum.jquery.com/topic/position-keeps-adding-original-left-and-top-to-current-values-in-ie-8
.css({'left':0,'top':0})
// position modal 10px to the right of the popup link
.position({'my':'left+10 center',
'at' : 'right center',
'of' : $(this)
}
).fadeIn();
},function(){
$('.modal.'+$(this).data('modal')).fadeOut();
});
(一定要包括jQuery UI的至少位置插件:http://jqueryui.com/download/#!version=1.11.0&components=0001000000000000000000000000000000000。是的,也许这有点矫枉过正,但它真的很方便)
考虑使用jQuery的'data'属性而不是类http://api.jquery.com/data/然后你可以做一些像'$(“。modal [data-popup ='“+”one“+”']“)。show()' – Greg
你想单独控制元素吗?如果是这样,你需要使用(当前)你的类来定位正确的元素。更好的方法是使用数据属性来区分它们并在弹出窗口和模态元素之间进行选择。见:http://jsfiddle.net/2PmnQ/4/ –
谢谢你们!更糟糕的是你的例子正是我所寻找的。但是,如何让定位工作?我尝试在上面的Gregs注释中输入数据选择器,但无法使其工作。所以这不起作用,但var p = $(“。popUp”,this);是沿着我需要的目标是“this”.popUp ......所以“一个”.model在第一行的右边,“two”在第二行的右边? – mike