jQuery捕获窗口调整大小片段

使用jQuery捕获调整浏览器窗口大小时的事件,然后执行某些操作。 在下面的示例中,它记录了窗口的新大小。

2013年6月5日更新:请参阅下面的反跳方法,以更智能地调整窗口大小!

//capture window resize
$(window).bind('resize', function(e)
{
    var win = $(this),
        w = win.width(),
        h = win.height();

    console.log('window resized to: ' + w + ' by ' + h);
});

//output: window resized to: 1598 by 521

刷新浏览器页面大小

一个漂亮的跨浏览器IE8 +解决方案。

//this is in a timeout so it works in IE8
setTimeout(function()
{
    $(window).bind('resize', function(e)
    {
        if(window.RT) clearTimeout(window.RT);
        window.RT = setTimeout(function()
        {
            this.location.reload(false); /* false to get page from cache */
        }, 300);        
    });
}, 1000);

调整窗口大小时重新定位导航栏的示例

调整窗口大小后,移动导航菜单栏。 稍微延迟300毫秒,但这是为了防止在调整浏览器大小时递归调用重新定位。

(function($,W)
{
    //DOM Ready
    $(function()
    {
        //responsive main nav absolute top position relative to window height
        function repositionMainNav()
        {
            var newT = W.innerHeight - 300;
            newT = (newT < 165) ? 165 : newT; //min top
            newT = (newT > 550) ? 550 : newT; //max top
            // console.log(newT);
            $('#navbar').css('top', newT);
        }
        repositionMainNav();

        $(W).bind('resize', function(e)
        {
            if(W.RT) clearTimeout(W.RT);
            W.RT = setTimeout(function()
            {
                //recalculate the vertical position of the main nav
                repositionMainNav();
            }, 300);
        });
    });
})(jQuery, window);

宣布“更智能”的窗口调整大小事件

感谢曾经杰出的保罗爱尔兰先生(Paul Irish)在他的退役职位上观看演示的实际情况

(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize 
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


// usage:
$(window).smartresize(function(){
  // code that takes it easy...
});

From: https://www.sitepoint.com/jquery-capture-window-resize/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值