jQuery读取窗口宽度 [英] jQuery read window width

查看:165
本文介绍了jQuery读取窗口宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些仅在窗口宽度小于768px时才运行的jQuery.我有以下代码

I'm trying to write some jQuery that is only run if the window width is below 768px. I have the following code

$(document).ready(function() {
    if($(window).width() <= 768){
       $("<p>Test</p>").insertBefore( "#menu-item-18 a" ); 
    }

});

但是,无论是将浏览器加载为< 768还是将浏览器的大小调整为< 768,我都无法使用它.

However I cannot get this to work whether the browser is loaded as <768 or when the browser is resized to <768.

我做错了什么?仅当浏览器宽度小于< 768时,如何才能识别窗口宽度并运行此jQuery?有没有更好的方法可以根据浏览器的宽度运行jQuery?

What am I doing wrong? How can I make it recognise the window width and run this jQuery only if the browser width is less than <768? Is there a better way to run jQuery based on browser widths?

JS小提琴示例: http://jsfiddle.net/franhaselden/jotq6hwf/

玩了很多之后,我发现这段代码确实可以运行,但是只有在主动调整浏览器的大小时才可以运行.如果它以< 768加载,则jQuery无法运行.

推荐答案

var w = window.innerWidth;
var h = window.innerHeight;

不需要jquery.

已更新事件监听器:

if(window.attachEvent) {
    window.attachEvent('onresize', function() {
        alert('attachEvent - resize');
    });
}
else if(window.addEventListener) {
    window.addEventListener('resize', function() {
        console.log('addEventListener - resize');
    }, true);
}
else {
    //The browser does not support Javascript event binding
}

这篇关于jQuery读取窗口宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆