如何在调整窗口大小之前检查宽度和高度?

时间:2016-04-21 12:37:45

标签: jquery

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

$(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 });
});

2 个答案:

答案 0 :(得分:1)

只需将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 });
});

答案 1 :(得分:0)

$(window).on('load resize', yourfunction);