jQuery event.pageX 屬性



jQuery 的event.pageX屬性用於查詢滑鼠指標相對於文件左側邊緣的水平位置。

當觸發諸如單擊、滑鼠移動等事件時,此 jQuery 屬性提供滑鼠指標的 X 座標。

語法

以下是 jQuery event.pageX屬性的語法:

event.pageX

引數

此屬性不接受任何引數。

返回值

此屬性返回滑鼠指標的水平位置。

示例 1

以下是 jQuery event.pageX屬性的基本示例:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Click the mouse pointer relative to the left edge of the document</p>
    <p>Mouse pointer x coordinate: <span></span></p>
    <script>
        $(document).click(function(){
            $('span').text(event.pageX);
        })
    </script>
</body>
</html>

輸出

上述程式返回單擊時滑鼠指標的 X 座標,相對於文件的左邊緣:


示例 2

以下是使用 jQuery event.pageX屬性的另一個示例。我們使用此屬性查詢特定區域內滑鼠指標的 X 座標:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        div{
            width: 300px;
            height: 300px;
            background-color: green;
        }
    </style>
</head>
<body>
    <p>Move the mouse pointer relative to the left edge in the below box</p>
    <p>Mouse pointer x coordinate: <span></span></p>
    <div>

    </div>
    <script>
        $('div').mousemove(function(){
            $('span').text(event.pageX);
        })
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個具有綠色背景的框。當滑鼠指標移動到框內時,將顯示 X 座標:


示例 3

讓我們結合event.pageXevent.pageY屬性來同時查詢 X 和 Y 座標,它們表示滑鼠指標的位置:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Move the mouse pointer on your browser screen</p>
    <p>X coordinate: Y coordinates <span></span></p>
    <div>

    </div>
    <script>
        $(document).mousemove(function(){
            $x = event.pageX;
            $y = event.pageY;
            $('span').text($x + " : " + $y);
        })
    </script>
</body>
</html>

輸出

當滑鼠指標在瀏覽器螢幕上移動時,X 和 Y 座標將顯示在螢幕上:


jquery_ref_events.htm
廣告