javascript - 滑鼠偏移量

zyljjf發表於2017-09-26
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            body{
                margin: 0;
                padding: 0;
            }
            div{
                width: 200px;
                height:200px;
                border: 1px solid #000000;
            }
        </style>
        <script>

            //判斷滑鼠是否按下
            var isDown = false;

            //實時監聽滑鼠位置
            var moveX = 0;
            var moveY = 0;

            //記錄滑鼠按下瞬間的位置
            var x = 0;
            var y = 0;

            滑鼠按下時移動的偏移量
            var mouseMoveX = 0;
            var mouseMoveY = 0;

        /*  function myWheel(){
                var cont = document.getElementById("cont"); 
                cont.style.fontSize = "40px";
            }
            */

            //滑鼠移動事件
            function myMove(event){
                moveX = event.clientX;
                moveY = event.clientY;
                var cont = document.getElementById("cont"); 
            var mess2 = document.getElementById("mess2");

                cont.innerHTML = "x="+moveX+",y="+moveY;

                //計算滑鼠移動偏移量
                mouseMoveX = moveX - x;
                mouseMoveY = moveY - y;

                if(isDown){
                    mess2.innerHTML = "滑鼠移動的偏移量為:x="+mouseMoveX+",y="+mouseMoveY;
                }


            }

            //滑鼠按下事件
        function myDown(event){
                x = event.clientX;
                y = event.clientY;
                isDown = true;

                var mess = document.getElementById("mess");
                mess.innerHTML = "滑鼠按下了,當前滑鼠位置:x="+x+",y="+y;
            }

            //滑鼠鬆開事件
            /*function myUp(){
                var mess = document.getElementById("mess");
                mess.innerHTML = "滑鼠鬆開了";
                isDown = false;
                mouseMoveX = 0;
                mouseMoveY = 0;
            }*/

        </script>
    </head>
    <body>

        <div id="cont" onwheel="myWheel()" onmouseup="myUp()" onmousedown="myDown(event)"  onmousemove="myMove(event)">

        </div>
        <font id="mess"></font><br>
        <font id="mess2"></font>

    </body>
</html>

這裡寫圖片描述

相關文章