通过JavaScript/jQuery实现的跨浏览器窗口大小调整事件

通过JavaScript/jQuery实现的跨浏览器窗口大小调整事件

resize()方法 是jQuery中的内置方法,用于当浏览器窗口改变大小时使用。resize()方法触发resize事件或附加一个函数以在发生resize事件时运行。jQuery有一个内置的窗口调整大小事件方法。

语法:

$(selector).resize(function)

这个语法用于跨浏览器的调整大小事件。

示例1: 这个示例使用resize()方法来计算浏览器窗口调整大小的次数。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
</script> 
<script> 
    var x = 1; 
    (document).ready(function() { 
        (window).resize(function() { 
            $("span").text(x += 1); 
        }); 
    }); 
</script> 
<p>Window resized <span>0</span> times.</p> 
<p>Try resizing your browser window.</p>

输出:

通过JavaScript/jQuery实现的跨浏览器窗口大小调整事件

您可以使用addEventListener()方法来注册事件处理程序,以侦听浏览器窗口调整大小事件,例如window.addEventListener(‘resize’, …)。

语法:

object.addEventListner("resize", myscript);

示例2: 该示例显示调整窗口的大小。

<div id="result"></div> 
  
<script> 
    // Defining event listener function 
    function displayWindowSize() { 
          
        // Get width and height of the window 
        // excluding scrollbars 
        var w = document.documentElement.clientWidth; 
        var h = document.documentElement.clientHeight; 
      
        // Display result inside a div element 
        document.getElementById("result").innerHTML 
            = "Width: " + w + ", " + "Height: " + h; 
    } 
      
    // Attaching the event listener function 
    // to window's resize event 
    window.addEventListener("resize", displayWindowSize); 
      
    // Calling the function for the first time 
    displayWindowSize(); 
</script> 
  
<p> 
    <strong>Note:</strong> Please resize the browser 
    window to see how it works. 
</p>

输出结果:

通过JavaScript/jQuery实现的跨浏览器窗口大小调整事件

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程