0

只要媒体查询,我正在使用一些javascript来检测宽度变化。我需要两者,因为我需要移动 html。两者都有效,除了它们发生的时间不一样,我猜测滚动条包含在其中一个中,但假设滚动条为 15px 是愚蠢的,因为它的宽度在浏览器中是不一样的。有更好的方法吗?

我的媒体查询是这样激活的:

<link rel="stylesheet" href="mobile.css" media="screen and (max-width: 767px)" />

并使用:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

虽然我的 JS 看起来像这样:

var delay = (function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

var pause = 100;
$(window).resize(function() {
    delay(function() {
        var width = $(window).width();
          if ( width >= 768 ) {
            if (window.myDevice != 'desktop' || window.myDevice === undefined) {
                window.myDevice = 'desktop';
                $('#head').prepend($('#branding'));
            }
        } else if ( width <= 767 ) {
            if (window.myDevice != 'mobile' || window.myDevice === undefined) {
                window.myDevice = 'mobile';
                $('#content').prepend($('#branding'));
            }
        }
    }, pause );
});

谢谢!

4

1 回答 1

0

使用在http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript找到的脚本,我已经解决了这个问题。

增加了功能

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

然后viewport().width在我的内部引用宽度,(window).resize()如下所示:

$(window).resize(function() {
    delay(function() {
        var width = $(window).width();
          if ( width >= 768 ) {
            if (window.myDevice != 'desktop' || window.myDevice === undefined) {
                window.myDevice = 'desktop';
                $('#head').prepend($('#branding'));
            }
        } else if ( width <= 767 ) {
            if (window.myDevice != 'mobile' || window.myDevice === undefined) {
                window.myDevice = 'mobile';
                $('#content').prepend($('#branding'));
            }
        }
    }, pause );
});
于 2013-10-25T19:44:41.223 回答