jQuery 事件 mouseout() 方法



jQuery 事件mouseout()方法為mouseout事件附加一個事件處理程式。當滑鼠指標離開所選元素或其任何子元素時,它將觸發。

它與jQuery mouseleave事件不同,後者僅在滑鼠指標離開所選元素本身時觸發。

語法

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

$(selector).mouseout(function)

引數

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

  • function − 當mouseout事件觸發時執行的可選函式。

返回值

此方法不返回任何值,而是將事件處理程式繫結到mouseout事件。

示例 1

以下示例演示了jQuery事件mouseout()方法的用法:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    p{
        background-color: green;
        padding: 10px;
        color: white;
        width: 300px;
    }
</style>
</head>
<body>
    <p>Enter and leave the mouse pointer on me</p>
    <script>
        $('p').mouseout(function(){
            alert("The mouse pointer leaves the selected element.")
        });
    </script>
</body>
</html>

輸出

上面的程式顯示一條訊息,當滑鼠指標離開顯示的訊息時,瀏覽器螢幕上將出現一個彈出警報訊息:


當滑鼠指標離開所選元素時:


示例 2

jQuery事件mouseout()方法可以處理父元素及其子元素之間的滑鼠互動:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 350px;
        padding: 20px;
        background-color: aqua;
    }
    p{
        background-color: green;
        padding: 10px;
        width: 300px;
    }
</style>
</head>
<body>
    <div class="parent">
        Parent
        <p class="child">Child</p>
    </div>
<script>
    $(document).ready(function() {
        $('.parent').mouseout(function() {
            $(this).css('background-color', 'lightgreen');
        });
        $('.child').mouseout(function() {
            $(this).css('color', 'white');
        });
    });
</script>
</body>
</html>

輸出

在上面的程式中,mouseout事件附加到父元素和子元素。當滑鼠指標離開父元素時,其背景顏色變為“淺綠色”。類似地,當滑鼠指標離開子元素時,其文字顏色變為“白色”。


示例 3

在下面的示例中,我們使用jQuery事件mouseout()方法來更改樣式並在滑鼠從輸入元素移出時列印輸入欄位的輸入文字:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>To change the input field style, simply move your mouse pointer away from the input field below.</p>
    <label for="">Name: </label>
    <input type="text"><br><br>
    <span></span>
<script>
    $('input').mouseout(function(){
        $(this).css(
            {
                "background-color": "lightgreen", 
                "color": "white", 
                "width": "300px", 
                "border-radius" : "10px", 
                "transition": "1s",
                "padding": "10px"
            });
        $value = $('input').val();
        $('span').text("Input data: " + $value);
    });
</script>
</body>
</html>

輸出

程式執行後,它會顯示一個輸入欄位。當滑鼠離開輸入欄位時,背景變為“綠色”,輸入的文字顯示在輸入欄位旁邊。


jquery_ref_events.htm
廣告
© . All rights reserved.