jQuery read window width

北城余情 提交于 2019-12-13 09:31:56

问题


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" ); 
    }

});

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

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?

Example JS Fiddle: http://jsfiddle.net/franhaselden/jotq6hwf/

Edit: having played around more I have discovered this code does run but ONLY when the browser is actively resized. If it is loaded at <768 then the jQuery does not run.


回答1:


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

No need for jquery.

UPDATED for eventlistener:

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
}



回答2:


$(function() {
    $(window).on('resize', function() {
        if($(window).width() >= 768){
           $("<p>Test</p>").insertBefore( "#menu-item-18 a" ); 
        }
    }).trigger('resize');
});


来源:https://stackoverflow.com/questions/28298175/jquery-read-window-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!