如果我的屏幕宽度小于960像素,我如何让jQuery做一些事情?下面的代码总是触发第二个警报,不管我的窗口大小:

if (screen.width < 960) {
    alert('Less than 960');
}
else {

    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>

其他回答

不,这些都没用。你需要的就是这个!!

试试这个:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}

你可能想把它和一个resize事件结合起来:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

R.J。:

var eventFired = 0;

if ($(window).width() < 960) {
    alert('Less than 960');

}
else {
    alert('More than 960');
    eventFired = 1;
}

$(window).on('resize', function() {
    if (!eventFired) {
        if ($(window).width() < 960) {
            alert('Less than 960 resize');
        } else {
            alert('More than 960 resize');
        }
    }
});

我尝试http://api.jquery.com/off/没有成功,所以我使用eventFired标志。

简单干净的解决方案使用香草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需要):

/*
 * 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/

使用jQuery获取窗口的宽度。

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}