javascript - 如果是同一个类(class),则淡入/淡出

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

);

最佳答案

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

<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 。是的,也许这有点过分了,但它确实很方便)

关于javascript - 如果是同一个类(class),则淡入/淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745844/

相关文章:

javascript - 在 AngularJS 中动态填充下拉列表

Javascript 检测浏览器滚动到顶部?

javascript - jQuery:如何在运行时插入或删除 .js 文件?

javascript - 从第二个下拉列表加载下拉列表 Ajax 到 PHP 不起作用

javascript - 垂直菜单/导航自动滚动

javascript - 存储 "last 10"数据集的数据结构?

jquery - 在 GAE 中找不到背景图像

javascript - 获取没有设置 css 的 div 的 .outerheight() 返回错误的数字

javascript - 屏幕外的 jquery 元素导致水平滚动

javascript - localStorage 存储大尺寸数据