jQuery mousedown() 事件方法



jQuery 事件mousedown() 方法用於將處理程式(函式)繫結到 mousedown 事件,或在選定元素上觸發該事件。

當滑鼠按鈕在選定元素上按下時觸發。通常,此方法與mouseup() 方法結合使用以處理滑鼠操作。

語法

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

$(selector).mousedown(function)

引數

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

  • function (可選) - 當觸發 mousedown 事件時要執行的可選函式。

返回值

此方法沒有任何返回值。

示例 1

以下程式演示了 jQuery 事件mousedown() 方法的使用:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        background-color: gray;
        color: white;
        padding: 10px;
    }
</style>
</head>
<body>
    <div>Press mouse down button on me..!</div>
    <script>
        $('div').mousedown(function(){
            alert("Mouse button pressed down...!");
        });
    </script>
</body>
</html>

輸出

以下程式在使用者按下滑鼠按鈕時顯示一條訊息,瀏覽器螢幕上將出現一個警報彈出視窗:


當用戶按下顯示的訊息上的滑鼠按鈕時:


示例 2

以下是 jQuery 事件mousedown() 方法的另一個示例。我們使用此方法來為特定按鈕觸發 mousedown 事件:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    span{
        color: green;
    }
</style>
</head>
<body>
    <p>Click on the below displayed button..</p>
    <button>Click me!</button>
    <span></span>
    <script>
        $('button').mousedown(function(){
            $('span').text("Button pressed down...!");
        });
    </script>
</body>
</html>

輸出

執行程式後,將出現一個按鈕。按下按鈕時,將在按鈕旁邊顯示一條綠色訊息:


當用戶按下顯示的按鈕時:


示例 3

使用mousedown() 方法更改表單輸入欄位的背景顏色:

<!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;
    }
    button{
        padding: 10px;
    }
</style>
</head>
<body>
    <p>Click on the below form input fields to change the different background</p>
   <form>
    <input type="text" placeholder="Username">
    <input type="password" placeholder="Password">
    <button>Login</button>
   </form>
    <script>
        $('input').mousedown(function(){
            $('input').css({"background-color" : "gray", "color": "white"});
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個包含兩個輸入欄位和一個按鈕的表單。當用戶單擊輸入欄位時,背景顏色將更改為“灰色”:


當用戶單擊輸入欄位時:


jquery_ref_events.htm
廣告