【问题标题】:How to check the width and the height before resizing the window?如何在调整窗口大小之前检查宽度和高度?
【发布时间】:2016-08-14 16:07:12
【问题描述】:

大家好,我有这个功能,可以在每次调整窗口大小时缩放容器。但是当我第一次加载页面时显示容器的原始大小。如何首先检查窗口的宽度和高度,然后在不调整窗口大小的情况下向我显示正确尺寸的容器?

$(window).resize(function(evt) {
    var $window = $(window);
    var width = $window.width();
    var height = $window.height();
    var scale;
    // early exit
    if(width >= maxWidth && height >= maxHeight) {
        $('#banner').css({'-webkit-transform': ''});
        $('#ad').css({ width: '', height: '' });
        return;
    } 
    scale = Math.min(width/maxWidth, height/maxHeight);
    $('#banner').css({'-webkit-transform': 'scale(' + scale + ')'});
    $('#ad').css({ width: maxWidth * scale, height: maxHeight * scale });
});

【问题讨论】:

  • 你应该使用media queries而不是Javascript
  • 这就是重点。我想使用没有 CSS 的 jQuery
  • 您可以在resize 中使用相同的代码并在load 上执行此操作
  • 为什么? CSS 比 Javascript 解决方案更好、更高效。

标签: jquery


【解决方案1】:
$(window).on('load resize', yourfunction);

【讨论】:

    【解决方案2】:

    只需将load 添加到您的函数中,例如:

    $(window).on('resize load', function(evt) {
        var $window = $(window);
        var width = $window.width();
        var height = $window.height();
        var scale;
        // early exit
        if(width >= maxWidth && height >= maxHeight) {
            $('#banner').css({'-webkit-transform': ''});
            $('#ad').css({ width: '', height: '' });
            return;
        } 
        scale = Math.min(width/maxWidth, height/maxHeight);
        $('#banner').css({'-webkit-transform': 'scale(' + scale + ')'});
        $('#ad').css({ width: maxWidth * scale, height: maxHeight * scale });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 2011-05-21
      • 2012-06-19
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多