问题
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