媒体查询和 JavaScript 窗口调整不同的宽度

Media queries plus javascript window resize different width

本文关键字:调整 查询 JavaScript 窗口 媒体      更新时间:2023-09-26

我正在使用一些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 );
});

谢谢!

使用在 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' ] };
}

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

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