jQuery resize() 事件方法



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

當瀏覽器視窗的大小發生變化時,將觸發“resize”事件。此事件通常用於增強網頁的響應能力,尤其是在調整導航欄以適應不同的螢幕尺寸時。

語法

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

$(selector).resize(function)

引數

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

  • function - 一個可選函式,每次觸發事件時都會執行。

返回值

此方法不返回值,但將事件處理程式繫結到 resize 事件。

示例 1

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

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Resize your window screen</p>
</body>
<script>
    $(window).resize(function(){
        alert("You resized the window screen");
    });
</script>
</html>

輸出

以上程式在視窗螢幕大小調整時顯示一個彈出警報訊息:


示例 2

當您的視窗螢幕大小調整時,更改 div 元素的背景顏色:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 60%;
        height: 300px;
        padding: 20px;
        background-color: gray;
    }
</style>
</head>
<body>
    <p>Resize your window screen</p>
    <div>
        Box
    </div>
</body>
<script>
    $(window).resize(function(){
       $('div').css("background-color", "green");
    });
</script>
</html>

輸出

執行程式後,將顯示一個框。當視窗大小調整時,該框的背景顏色將更改為綠色:


示例 3

當視窗大小調整時隱藏導航欄,並透過單擊按鈕再次顯示它:

<!DOCTYPE html>
<html>	
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 100%;
        padding: 10px;
        background-color: gray;
    }
    div ul{
        list-style: none;
        text-align: right;
    }
    div ul li{
        display: inline-block;
        margin: 0px 10px;
    }
    .demo{
        width: 100%;
        text-align: left;
        padding: 10px;
    }
    .demo ul{
        display: none;
    }
</style>
</head>
<body>
    <div>
        <ul>
            <li>HOME</li>
            <li>ABOUT US</li>
            <li>BLOG</li>
            <li>CONTACT US</li>
        </ul>
    </div>
    <div><button>Click</button></div>
</body>
<script>
    $(window).resize(function(){
        $('div').toggleClass('demo');
    });
    $('button').click(function(){
        $('ul').slideDown();
    });
</script>
</html>

輸出

程式執行後,將顯示導航欄和一個按鈕。當視窗大小調整時,導航欄將被隱藏。要再次顯示它們,請單擊顯示的按鈕:


jquery_ref_events.htm
廣告

© . All rights reserved.