关于鼠标延迟

来源:互联网 发布:乔治格文最佳数据 编辑:程序博客网 时间:2024/04/29 17:56
<!DOCTYPE html>
<html>
<head>
    <title>div change</title>
    <!-- 一般在动态菜单或图片切换使用这种效果 -->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript" src="jquery-2.0.0.min.js"></script>
        <script type="text/javascript">
             window.open("http://www.baidu.com"); 
        </script>
</head>
<body>
    <center>
    <div id="div1" style="width:200px;height:200px;border:black 1px dotted"></div>
    <select id="color">
    <option value="white">默认</option>
    <option value="black">黑色</option>
    <option value="blue">蓝色</option>
    <option value="orange">橙色</option>
    </select></br>
    <input type="button" id="choice" value="更改背景色"/>
    </center>
    <script type="text/javascript">
        $(function(){
        //当文档加载完成时绑定要执行的函数,极大地提高web程序的响应速度,替代window.load,在DOM就绪,能相应执行的时候立即调用(回调函数)
        $("#choice").click(function(){
        // div选取包括click事件和鼠标悬停mouseover事件
         //mouseover 和hover区别  hover还包括了mouseout效果,并修正了mouseout的一些错误
         //hover(fn(){over},fn(){out})  out修正了鼠标离开事件
        $("#div1").css({background:$('#color').val()});
        // alert($("#color").val());
        });
        });
    </script>
</body>

</html>

鼠标经过事件为web页面上非常常见的事件之一。简单的hover可以用CSS :hover伪类实现,复杂点的用js。

说到延时,离不开window下的setTimeout方法,本实例的jQuery方法的核心也是setTimeout。代码不长,完整如下:

(function($){    $.fn.hoverDelay = function(options){        var defaults = {            hoverDuring: 200,            outDuring: 200,            hoverEvent: function(){                $.noop();            },            outEvent: function(){                $.noop();                }        };        var sets = $.extend(defaults,options || {});        var hoverTimer, outTimer;        return $(this).each(function(){            $(this).hover(function(){                clearTimeout(outTimer);                hoverTimer = setTimeout(sets.hoverEvent, sets.hoverDuring);            },function(){                clearTimeout(hoverTimer);                outTimer = setTimeout(sets.outEvent, sets.outDuring);            });            });    }      })(jQuery);
摘自http://www.zhangxinxu.com/wordpress/2010/07/jquery-%E9%BC%A0%E6%A0%87%E7%BB%8F%E8%BF%87hover%E4%BA%8B%E4%BB%B6%E7%9A%84%E5%BB%B6%E6%97%B6%E5%A4%84%E7%90%86/

这段代码的目的在于让鼠标经过事件和延时分离的出来,延时以及延迟的清除都已经由此方法解决了。您所要做的,就是设定延时的时间大小,以及相应的鼠标经过或是移除事件即可。举个简单的例子吧,如下代码:

$("#test").hoverDelay({    hoverEvent: function(){        alert("经过我!");    }});
hoverDuring       鼠标经过的延时时间
outDuring          鼠标移出的延时时间
hoverEvent        鼠标经过执行的方法
outEvent         鼠标移出执行的方法
原创文章,转载请注明来自张鑫旭-鑫空间-鑫生活[http://www.zhangxinxu.com]

http://www.zhangxinxu.com/wordpress/?p=906

0 0