我在 jsFiddle 中有一个设置:http://jsfiddle.net/2PmnQ/
我正在尝试创建一个函数来检查模态是否与按钮具有相同的类,以便按钮将调出具有相同类的模态。显然,我试图在一个函数中动态地执行此操作,而不是为每个类执行 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 。是的,也许这有点过分了,但它确实很方便)
关于javascript - 如果是同一个类(class),则淡入/淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745844/