获取上一个和当前窗口宽度

时间:2012-08-29 19:11:55

标签: javascript jquery resize

我正试图通过JS获取之前和当前的窗口宽度。我使用jQuery捕获窗口大小调整事件。这是我的代码:

<script>
 function getWindowWidth() {
   var myWidth = 0, myHeight = 0;
     if( typeof( window.innerWidth ) == 'number' ) {
         myWidth = window.innerWidth; myHeight = window.innerHeight;
     } else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
         myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
     } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
         myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
     }
     return myWidth;
 }
 var lastWindowWidth;
 $(document).ready(function() {
   $(window).resize(function() {
       $('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + getWindowWidth());
       lastWindowWidth = getWindowWidth();
     });
 });
</script>

它让我回复:

Previous: 1685 Current: 1685

为什么Previous和Current:值相似?提前谢谢!

3 个答案:

答案 0 :(得分:9)

使用jQuery。

所以使用jQuery:

$(window).width();

 var lastWindowWidth;
 $(document).ready(function() {
   $(window).resize(function() {
       var $window = $(this),
           windowWidth = $window.width();
       $('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + windowWidth );
       lastWindowWidth = windowWidth;
     });
 });

小提琴:http://jsfiddle.net/maniator/pKfSN/5/

答案 1 :(得分:2)

答案的本质是在调整窗口大小之前捕获previous_window_width

var previous_window_width = $(window).width();

...

$(window).resize(function() {
    var current_window_width = $(window).width();
    // do whatever you need with previous_window_width
});

答案 2 :(得分:0)

这里你去http://jsfiddle.net/B9chY/

var lastWindowWidth = $(window).width();

$(window).resize(function() {
   $('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + $(window).width());
       lastWindowWidth = $(window).width();
 });

基于评论:

var lessThan = false;

$(document).ready(function() {
    if ($(window).width() < 980) {
        lessThan = true;
    }
});

$(window).resize(function() {
   if ($(window).width() < 980) {
        lessThan = true;
    }
});