遇到jQuery 中的 slideUp ,slideToggle和 slideDown 动画重复执行

说明

jQuery 可以通过调用 animate 方法添加动画效果, 而且还提供了一套别名, 使用起来很是方便. 其中 slideDown和 slideUp 两方法的作用是纵向展开和卷起一个页面元素, 被使用的几率很高, 却一直存在一个小问题.

如果目标元素是被外部事件驱动, 当鼠标快速地连续触发外部元素事件, 动画会滞后的反复执行, 相当不美观 演示页面中有一个按钮, 请用鼠标迅速地来回划过…

如果用 jQuery 来实现这样的效果, 该如何处理呢?
其实很简单, 只需在触发元素上的事件设置为延迟处理, 即可避免滞后反复执行的问题. 例如: 当鼠标滑过按钮后 0.2 秒, 菜单才会展开, 如果鼠标离开按钮, 展开的处理将被终止. 也就是说, 想要展开菜单鼠标必须有 0.2 秒的事件停留在按钮上, 那么迅速地划过按钮是无法执行展开事件的. 卷起也是如此.

代码演示

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    p {display: none;}
    </style>
</head>
<body>
    <div id="menu">
        <ul>
            <li>
                <h1>
                    aaaaaa
                </h1>
                <p>
                    this is aaaa test. this is aaaa test. this is aaaa test. this is aaaa test.
                </p>
            </li>
            <li>
                <h1>
                    bbbbb
                </h1>
                <p>
                    this is bbbbb test. this is bbbbb test. this is bbbbb test. this is bbbbb test.
                </p>
            </li>
            <li>
                <h1>
                    cccccc
                </h1>
                <p>
                    this is bbbbb test.
                </p>
            </li>
            <li>
                <h1>
                    ddddddd
                </h1>
                <p>
                    this is ddddddd test.
                </p>
            </li>
        </ul>
    </div>
    <script src="//cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
    <script>

    var mouseover_tid = [];
    var mouseout_tid = [];

    $(document).ready(function() {

        $('#menu li').each(function(index) {

            $(this).hover(
                // 鼠标进入        
                function() {
                    var _self = this;
                    // 停止卷起事件      
                    clearTimeout(mouseout_tid[index]);
                    // 当鼠标进入超过 0.2 秒, 展开菜单, 并记录到线程 ID 中        
                    mouseover_tid[index] = setTimeout(function() {
                        $(_self).find('p').slideDown(500);
                    }, 200);
                },
                // 鼠标离开             
                function() {

                    var _self = this;

                    // 停止展开事件          
                    clearTimeout(mouseover_tid[index]);

                    // 当鼠标离开超过 0.2 秒, 卷起菜单, 并记录到线程 ID 中            
                    mouseout_tid[index] = setTimeout(function() {
                        jQuery(_self).find('p').slideUp(500);
                    }, 200);
                }
            );
        });
    });
    </script>
</body>

</html>

参考 : 文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值