如果我的屏幕宽度小于960像素,我如何让jQuery做一些事情?下面的代码总是触发第二个警报,不管我的窗口大小:
if (screen.width < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
如果我的屏幕宽度小于960像素,我如何让jQuery做一些事情?下面的代码总是触发第二个警报,不管我的窗口大小:
if (screen.width < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
当前回答
你也可以用javascript来使用媒体查询。
const mq = window.matchMedia( "(min-width: 960px)" );
if (mq.matches) {
alert("window width >= 960px");
} else {
alert("window width < 960px");
}
其他回答
use
$(window).width()
or
$(document).width()
or
$('body').width()
试试这段代码
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
If ($(window).width() < 960) { 警报('宽度小于960px'); } 其他{ alert('大于960'); } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>
使用jQuery获取窗口的宽度。
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
// Adds and removes body class depending on screen width.
function screenClass() {
if($(window).innerWidth() > 960) {
$('body').addClass('big-screen').removeClass('small-screen');
} else {
$('body').addClass('small-screen').removeClass('big-screen');
}
}
// Fire.
screenClass();
// And recheck when window gets resized.
$(window).bind('resize',function(){
screenClass();
});
我建议(jQuery需要):
/*
* windowSize
* call this function to get windowSize any time
*/
function windowSize() {
windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
}
//Init Function of init it wherever you like...
windowSize();
// For example, get window size on window resize
$(window).resize(function() {
windowSize();
console.log('width is :', windowWidth, 'Height is :', windowHeight);
if (windowWidth < 768) {
console.log('width is under 768px !');
}
});
在CodePen中添加: http://codepen.io/moabi/pen/QNRqpY?editors=0011
然后你可以用var: windowWidth很容易地得到窗口的宽度 和高度:windowHeight
否则,获取一个js库: http://wicky.nillia.ms/enquire.js/