1. 程式人生 > 實用技巧 >滑鼠事件考

滑鼠事件考

滑鼠事件有一下幾種

  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{
         width: 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>