• jQuery Video Tutorials

jQuery 事件 mouseenter() 方法



jQuery 事件mouseenter() 方法用於將事件處理程式附加到 mouseenter 事件,或者在滑鼠指標進入選定元素時觸發。

mouseenter() 方法類似於 mouseover() 方法;這兩者之間的區別在於 mouseover 事件會冒泡,而 mouseenter 事件不會。

語法

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

$(selector).mouseeneter(function)

引數

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

  • function - 一個可選的函式,在 mouseenter 事件發生時執行。

返回值

此方法不返回值,但會將事件處理程式附加到 mouseenter 事件。

示例 1

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

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Mouse pointer enter on me!</p>
    <script>
        $('p').mouseenter(function(){
            alert("Mouse pointer enter on the selected element..!");
        });
    </script>
</body>
</html>

輸出

以上程式會在滑鼠指標進入(或懸停)顯示的訊息時顯示一條訊息,瀏覽器螢幕上會出現一個彈出警報:


當滑鼠指標進入選定元素時:


示例 2

以下是 jQuery 事件mouseenter() 方法的另一個示例。在這裡,當滑鼠指標進入(或懸停)輸入欄位時,我們更改輸入欄位的背景顏色:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Hovers the mouse pointer on the below input field</p>
    Name: <input type="text" placeholder="Name">
    <script>
        $('input').mouseenter(function(){
            $(this).css({"background-color": "green", "color": "white"});
        });
    </script>
</body>
</html>

輸出

執行以上程式後,將顯示一個輸入欄位,當滑鼠指標進入輸入元素時:


當滑鼠指標進入輸入欄位時:


示例 3

讓我們看看 jQuery 事件mouseenter() 方法的另一種情況。在這裡,我們結合使用 mouseenter 和 mouseover 事件來切換元素的樣式:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    .enter{
        width: 250px;
        background-color: green;
        color: white;
        border-radius: 5px;
        padding: 10px;
        transition: 1s;
    }
    .leave{
        width: 200px;
        background-color: rgb(63, 77, 63);
        color: white;
        border-radius: 10px;
        transition: 0.5s;
        padding: 12px;
    }
</style>
</head>
<body>
    <p>Enter and leave mouse pointer on button to toggle the styles</p>
    <button>Toggle my Styles</button>
    <script>
        $('button').mouseenter(function(){
            $(this).addClass('enter');
        }).mouseleave(function(){
            $(this).addClass('leave');
        });
    </script>
</body>
</html>

輸出

執行以上程式後,它會顯示一個按鈕,當滑鼠指標進入按鈕元素時,背景變為“綠色”,當離開時背景變為“黑色”:


jquery_ref_events.htm
廣告

© . All rights reserved.