javascript - 第二次绑定事件失效

查看:137
本文介绍了javascript - 第二次绑定事件失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

第一次执行一切正常,第二次就不行了。

<style>    
        .out{width: 508px;background: pink;overflow:hidden;position: absolute;}
        .line{width: 500px;height: 100px;background: green;border:4px solid orange;margin:10px 0;position: relative;}
</style>
 </head>
 <body id="body"> 
    <div id="out"  class="out">    
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
    </div>
    
<script>
    //dom获取id方法
    function $(element){return document.getElementById(element);}
    //dom获取class方法
    function cl(element){return document.getElementsByClassName(element);}
    //移动方法
    function move(){    
        cl("line")[2].style.top = event.clientY - thistop + "px";
    }

    function md(){        
        thistop = cl("line")[2].getBoundingClientRect().top;
        $("out").addEventListener("mousemove",move)
    }

    function cancelmd(){        
        $("out").removeEventListener("mousemove",move)
    }

    cl("line")[2].addEventListener("mousedown",md)

    cl("line")[2].addEventListener("mouseup",cancelmd)

</script>
 </body>

解决方案

不是不生效,而是你move函数设计有问题,有时会出现mousedown之后,第三个方块已经脱离了你鼠标的范围,而且由于你的move函数的计算导致鼠标再也无法指到打三个方块了,自然第三个方块的mouseup事件无法触发;
你试试在你觉得不生效的时候,控制台输入

$("out").removeEventListener("mousemove",move);

这篇关于javascript - 第二次绑定事件失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆