jQuery hover() 方法



jQuery 事件hover() 方法用於為選定的元素繫結一個或兩個處理程式函式。第一個函式在滑鼠指標進入元素時執行,第二個函式(可選)在滑鼠指標離開元素時執行。

語法

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

$(selector).hover(functionIn, functionOut);

引數

此方法接受兩個名為“functionIn”和“functionOut”的引數,如下所述:

  • functionIn - 指定滑鼠指標進入元素時要執行的函式。
  • functionOut (可選) - 指定滑鼠指標離開元素時要執行的函式。

返回值

此方法不返回任何值,但會將一個或多個函式附加到選定的元素。

示例 1

當僅將functionIn引數傳遞給此方法時,它將在滑鼠指標進入元素時執行。

下面的程式演示了 jQuery 事件hover() 方法的用法。當我們只將一個 functionIn 引數傳遞給此方法時,它會在指標進入元素時執行,並且每次指標離開後重新進入元素時也會執行:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    .demo{
        background-color: green;
        color: white;
        width: 100px;
        padding: 10px;
    }
</style>
</head>
<body>
    <p>Hover on the below element to see the hover effect.</p>
    <div class="demo">TutorialsPoint</div>
    <script>
        $('div').hover(function(){
            $(this).css("background-color", "lightblue");
        });
    </script>
</body>
</html>

輸出

上面的程式顯示一條帶有綠色背景和白色文字的訊息:


當用戶將滑鼠懸停在元素上時,背景顏色將更改:


示例 2

使用按鈕元素。

當將functionInfunctionOut兩個引數都傳遞給此方法時,它最初在滑鼠指標進入元素時執行functionIn,然後在滑鼠指標離開元素時執行functionOut:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    button{
        background-color: rgb(12, 51, 12);
        color: white;
        width: 100px;
        padding: 10px;
        cursor: pointer;
        border-radius: 10px;
        transition: 0.5s;
    }
</style>
</head>
<body>
    <p>Hover on the below element to see the hover effect.</p>
    <button>Hover me!</button>
    <script>
        $('button').hover(function(){
            $(this).css("border-radius", "0px");
            $(this).css("width", "200px");
            $(this).css("background-color", "green");
        }, function(){
            $(this).css("border-radius", "10px");
            $(this).css("width", "100px");
            $(this).css("background-color", "black");
        });
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個具有黑色背景顏色的按鈕。當用戶將滑鼠懸停在其上時,寬度將擴充套件到 200px,背景顏色將更改為綠色:


當用戶離開元素時:


示例 3

使用輸入欄位。

在下面的示例中,我們使用 jQuery hover() 方法來附加一個或多個函式。第一個函式在使用者進入輸入欄位時執行,第二個函式在使用者離開輸入欄位時執行:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    input{
        padding: 10px;
    }
</style>
</head>
<body>
    <input type="text" placeholder="Username">
    <input type="text" placeholder="Password">
    <script>
        $('input').hover(function(){
            $(this).css("border-radius", "0px");
            $(this).css("width", "200px");
        }, function(){
            $(this).css("border-radius", "10px");
            $(this).css("width", "100px");
        });
    </script>
</body>
</html>

輸出

上面的程式顯示兩個輸入欄位:


當用戶將滑鼠懸停在輸入欄位上時:


當用戶離開輸入欄位時:


jquery_ref_events.htm
廣告