且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery在窗口调整大小

更新时间:2023-02-05 22:32:44

下面是一个使用jQuery,javascript和css来处理大小调整事件的例子。

(css if you best bet bet if you 只是在调整大小(媒体查询)的样式化样式)

http://jsfiddle.net/CoryDanielson/LAF4G /

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
          bottom: 3px;
          left: 0px;
        /* more styles */
    }
}



javascript



javascript

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}



jQuery



jQuery

$(window).on('resize', function(){
      var win = $(this); //this = window
      if (win.height() >= 820) { /* ... */ }
      if (win.width() >= 1280) { /* ... */ }
});



如何阻止调整大小的代码执行这么频繁?



这是你绑定到调整大小时你会注意到的第一个问题。

How do I stop my resize code from executing so often!?

This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

要调整调整大小的代码的频率,您可以使用调整大小的代码。 去抖限幅方法从下划线& lowdash 图书馆。

To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.


  • debounce 只会在LAST调整大小事件后的几毫秒内执行调整大小代码X.当用户调整浏览器大小后,您只想调用大小调整代码一次,这是理想的选择。

  • throttle 只会执行调整大小的动作,因此更新图表,图表和版面配置代码每X个毫秒。它调节代码被调用的频率。

  • debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.

如果没有下划线或lowdash, ,你可以自己实现一个类似的解决方案:
JavaScript / JQuery:$(window).resize在调整大小完成后如何触发?

If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?