鼠标事件考

鼠标事件有一下几种

  1.click  单击

  2.dblclik  双击

  3.mousedown  鼠标三键其中之一 按下

  4.mouseup  鼠标释放  

  5.mouseover  鼠标进入

  6.mouseout  鼠标离开

    5.6:鼠标移动到自身时候会触发事件,同时移动到其子元素身上也会触发事件,也就是说e.target改变了就会触发

  7.mouseenter  鼠标滑入

  8.mouseleave  鼠标滑出

    7,8鼠标移动到自身时候会触发事件,同时移动到子元素上不会触发事件。

  9.cintent  鼠标右键菜单事件。

  10.mousemove  鼠标在目标上移动事件

   事件触发顺序是:mousedown -> mouseup -> click -> mousedown -> mouseup -> click -> dblclick。

全局事件对象event

  e.y e.x e.clientX e.clientY 鼠标相对文档在左上顶不位置(当有滚动条或者滚动条改变时,注意)

  e.pageX e.pageY   鼠标相对于页面左上角位置

  e.offsetX e.offsetY  鼠标距离侦听目标的左上角位置

  e.layerX e.laerY  容器内元素针对侦听目标的左上角位置

  e.screenX e.screenY   针对显示屏的左上角位置

  e.movementX e.movementY  本次鼠标移动距离(mousemove)

  e.controlkey e.shiftkey e.altkey  鼠标事件触发时,按下了键盘上的那个辅助键

  e.button  鼠标的哪一个键触发的事件 0-左键  1-中键  2-右键

  我们上次学了一个阻止事件的冒泡 e.stopPropagation()

    这次我们学一个阻止默认行为e.proeventDefault()

    <form action="http://www.baidu.com" method="get">
        <input type="text" name="aa" id="">
        <!-- 当我们点击了 提交有 页面就会跳转到baidu的页面 -->
        <input type="submit" value="提交">
    </form>

    <script>
        var btn=document.querySelector("[type=submit]");
        btn.addEventListener("click",clickHandler);

        function  clickHandler(e){
            //阻止submit的默认行为,因为submit 系统默认就会跳转到action
            e.preventDefault();
            console.log("aaaa");
        }
    </script>

案例:

  放置一个div,让div跟随鼠标移动

 <style>
     div{
          50px;
         height:50px;
         background-color: red;
         position: absolute;
     }
 </style>
</head>
<body>
    
    <div></div>

    <script>
        var div=document.querySelector("div");
        
        document.addEventListener("mousemove",mouseHandler);
        function mouseHandler(e){
            //注意 这里一定要加px,offsetwidth/2 这样鼠标就会在div的中间了
            div.style.left=e.clientX-div.offsetWidth/2+"px";
            div.style.top=e.clientY-div.offsetHeight/2+"px";            
        }
    </script>
原文地址:https://www.cnblogs.com/xiaowie/p/13704116.html