2014-12-02 74 views
0

我有這樣的劇本,我希望在窗口只有不到768pxconsole.log('less than 768px');但我的腳本作品一貫窗口時,更多的則是768px,請幫助我的人:(

var width = $(window).width(); 
    $(window).on('resize',function(){ 
     if (width < 768){ 
      console.log('less than 768px'); 
     }else{ 
      console.log('nothing'); 
     } 
    }); 
+0

時,該工作......和你在哪裏獲得寬度的值?! – 2014-12-02 13:17:00

+0

您可以發佈可以使用的值的原點: var width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth; – 2014-12-02 13:17:07

+0

查看更新請 – 2014-12-02 13:18:44

回答

1

你需要得到調整大小事件回調內部寬度得到更新值:

$(window).on('resize',function(){ 
    var width = $(window).width(); 
    if (width < 768){ 
     console.log('less than 768px'); 
    }else{ 
     console.log('nothing'); 
    } 
}); 
2

您需要在resize處理程序中設置width變量,否則它僅使用頁面加載時設置的窗口寬度。

$(window).on('resize',function(){ 
    var width = $(window).width(); 

    if (width < 768){ 
     console.log('less than 768px'); 
    } else { 
     console.log('nothing'); 
    } 
}); 
+0

謝謝你<3 – 2014-12-02 13:21:34

+0

很高興能幫到:) – 2014-12-02 13:22:40

1

設置寬度值

$(window).resize(function(){ 
    var width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth; 
if (width < 768){ 
    console.log('less than 768px'); 
} else{ 
    console.log('nothing'); 
} 
}) 
+0

'var width = $(window).width();'有點短。 – Regent 2014-12-02 13:22:19