5

I'm trying to get previous and current window width via JS. I use jQuery for capturing window resize event. Here's my code:

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

It returns me:

Previous: 1685 Current: 1685

Why both Previous: and Current: values are similar? Thanks in advance!

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 に答える