0

jQueryでウィンドウサイズを取得できますか?

winWidth = $(window).width();
        
$("#status").text(winWidth);

これを挿入しましたが、一度しか取得できません。ウィンドウを縮小しても、値は同じです。この「イベント」が常にリスナーになる方法はありますか?

4

3 に答える 3

2

jQueryでイベントを使用.resize()します。ウィンドウのサイズを変更するたびにサイズが更新されます。あなたの場合は固定されています。ページの読み込み中に計算されます。したがって、ウィンドウのサイズが変更されたときにそのサイズを更新する必要があります。

var winWidth  = 0;
$(window).resize(function() {
  winWidth = $(window).width();
  $("#status").text(winWidth);
});
于 2013-05-23T09:24:25.590 に答える
0

jqueriesresize()イベントを使用します。

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

$(window).resize(function(){
    winWidth = $(window).width();
});
于 2013-05-23T09:27:04.553 に答える
-1

サイズ変更イベントにフックして、変更ごとに多くの処理を行うと、サイズ変更イベントがデスクトップで毎秒数百回トリガーされるため、ブラウザーがフリーズします。

関数でデバウンスを行う必要があります。

function updateOrientation() {
    // Detect whether device supports orientationchange event, otherwise fall back to the resize event
    // Genius solution from http://stackoverflow.com/a/2307936
    var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize", newAngle;

    if(supportsOrientationChange){
        newAngle = window.orientation;
        switch(newAngle){
            case 0:
            case 180: newOrientation = 'portrait'; break;
            case 90:
            case -90: newOrientation = 'landscape'; break;
        }
    } else {
        if(document.width < document.height){
            newOrientation = 'portrait'
        } else {
            newOrientation = 'landscape'
        }
    }

    // Do some processing here

    /*
     * Beautiful debouncing for resize event firing too much on the PC
    * by Pim Jager http://stackoverflow.com/a/668185/930987
    */
    resizeEvent = false;

    window.addEventListener(orientationEvent, function() {
        if(!resizeEvent) {
            clearTimeout(resizeEvent);
            resizeEvent = setTimeout(updateOrientation, 500)
        }
    })
   }
于 2013-05-23T09:31:18.723 に答える