5

我正在尝试通过 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: 值都相似?提前致谢!

4

3 回答 3

11

正在使用 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/

于 2012-08-29T19:15:00.690 回答
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
});
于 2014-12-12T08:08:44.340 回答
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;
    }
});
于 2012-08-29T19:18:45.127 回答