jQuery 事件 mouseleave() 方法



jQuery 事件 mouseleave() 方法用於將事件處理程式附加到 mouseleave 事件,或在選定元素上觸發該事件。當滑鼠指標離開選定元素時,就會發生此事件。

語法

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

$(selector).mouseleave(function)

引數

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

  • function − 一個可選函式,在 mouseleave 事件觸發時執行。

返回值

此方法沒有任何返回值。

示例 1

下面的程式演示了 jQuery 事件 mouseleave() 方法的用法:

<!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;
        color: white;
        background-color: green;
        text-align: center;
    }
</style>
</head>
<body>
    <div>Enter mouse pointer on me and leave</div>
    <script>
        $('div').mouseleave(function(){
            alert("Mouse pointer leaves the div element");
        });
    </script>
</body>
</html>

輸出

執行上述程式碼後,將顯示一個具有綠色背景的框。當滑鼠指標離開該框(即 div 元素)時,瀏覽器螢幕上將出現一個彈出式警報:


示例 2

讓我們看看 jQuery 事件 mouseleave() 方法的另一種情況。在這裡,我們根據給定的條件更改輸入欄位背景:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    input{
        width: 200px;
        padding: 10px;
    }
</style>
</head>
<body>
    <p>Enter input to check whether it satisfies the given condition or not</p>
    <input type="text" placeholder="Enter your name....">
    <script>
        $('input').mouseleave(function(){
            $value = $('input').val();
            if($value.length < 5){
                $(this).css({"background-color": "red", "color": "white"});
            }
            else{
                $(this).css({"background-color": "green", "color": "white"});
            }
        });
    </script>
</body>
</html>

輸出

程式顯示一個輸入欄位;當用戶離開輸入欄位時,背景變為紅色。如果輸入值的長度大於 5,則背景變為綠色:


示例 3

在下面的示例中,我們將 mouseleave()mouseenter() 方法結合起來,切換文字區域欄位的樣式:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    textarea{
        padding: 20px;
    }
</style>
</head>
<body>
    <p>Write your feedback...</p>
    <textarea name="" id="" cols="30" rows="10"></textarea>
   <script>
    $('textarea').mouseenter(function(){
        $(this).css({"width": "300px", "color": "white", "background-color": "green", "transition": "1s"});
    }).mouseleave(function(){
        $(this).css({"width": "200px", "color": "black", "background-color": "lightblue", "transition": "1s"});
    });
   </script>
</body>
</html>

輸出

程式執行後,它會顯示一個文字區域欄位。當用戶進入或離開此欄位時,文字區域欄位的寬度、顏色和背景顏色將相應更改:


jquery_ref_events.htm
廣告
© . All rights reserved.