如果我的屏幕宽度小于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');
}
当前回答
不,这些都没用。你需要的就是这个!!
试试这个:
if (screen.width <= 960) {
alert('Less than 960');
} else if (screen.width >960) {
alert('More than 960');
}
其他回答
简单干净的解决方案使用香草JavaScript
let app = document.getElementById('app') const changeColorFn = ( app, color ) => { app.setAttribute("style",`background: ${color}`) } const winSizeFn = ( winWidth, callback, app, color ) => { if (window.innerWidth < winWidth ) { callback(app, color); } } winSizeFn( '1200', changeColorFn, app, 'red' ) winSizeFn( '800', changeColorFn, app, 'green' ) winSizeFn( '500', changeColorFn, app, 'blue' ) window.addEventListener("resize", (e) => { // add winSizeFn here if you want call function on window resize }) <div id="app">My app content</div>
我建议不要使用jQuery来做这样的事情,而是继续使用window.innerWidth:
if (window.innerWidth < 960) {
doSomething();
}
// 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获取窗口的宽度。
if ($(window).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");
}