如果是同一个类,fadeIn / fadeout

时间:2014-07-14 20:56:54

标签: javascript jquery

我在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();
    }

);

1 个答案:

答案 0 :(得分:3)

我会使用自定义数据属性而不是类来保存目标类:

<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();
});

http://jsfiddle.net/2PmnQ/1/


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();
});

http://jsfiddle.net/2PmnQ/10/

(一定要包含jQuery UI至少包含位置插件:http://jqueryui.com/download/#!version=1.11.0&components=0001000000000000000000000000000000000。是的,这可能有点矫枉过正,但这真的很方便)