jQuery 事件 mousemove() 方法



jQuery 事件mousemove() 方法用於將事件處理程式繫結到 mousemove 事件或在選定的元素上觸發該事件。當滑鼠指標在選定的元素內移動時,就會發生此事件。

語法

以下是 jQuery 事件mousemove() 方法的語法:

$(selector).mousemove(function)

引數

此方法接受一個可選的引數作為函式,如下所述:

  • function - 當 mousemove 事件發生時要執行的可選函式。

返回值

此方法沒有任何返回值。

示例 1

以下是 jQuery 事件mousemove() 方法的基本示例:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 300px;
        padding: 20px;
        background-color: green;
        color: white;
    }
</style>
</head>
<body>
    <div>Move the mouse pointer within this box</div>
    <script>
        $('div').mousemove(function(){
            alert("Mouse pointer moved");
        });
    </script>
</body>
</html>

輸出

以上程式顯示了一個框,當滑鼠指標在框內移動時,瀏覽器螢幕上會出現一個彈出警報訊息:


當滑鼠指標在顯示的框內移動時:


示例 2

在下面的示例中,當滑鼠在 'p' 元素內移動時,我們更改了它的樣式:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Mouse move to change style</p>
    <script>
        $('p').mousemove(function(){
            $(this).css({
                'color' : 'green', 
                'font-style':'italic',
                'font-size': '30px',
                'font-weight': 'bold'
            });
        });
    </script>
</body>
</html>

輸出

執行以上程式後,會顯示一段文字,滑鼠在文字內移動,顯示文字的樣式將發生改變:


示例 3

讓我們看看 jQuery 事件mousemove() 方法的另一種情況。使用此方法,我們嘗試跟蹤滑鼠指標的位置:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    span{
        width: 300px;
        height: 50px;
        background-color: aqua;
        padding: 20px;
    }
</style>
</head>
<body>
    <p>Move your mouse pointer and see the pointer position</p><br>
    <span>X: 0, Y: 0
    </span>
    <script>
        $(document).mousemove(function(){
            $("span").text("X: " + event.pageX + ", Y: " + event.pageY);
        });
    </script>
</body>
</html>

輸出

執行以上程式後,它會顯示一個框。當滑鼠指標在瀏覽器螢幕上移動時,指標的位置將顯示在框本身內:


jquery_ref_events.htm
廣告