2013-04-11 68 views
3

我有下面的代碼來捕獲瀏覽器調整大小事件。當調整窗口大小時,css(「position」)返回undefined

window.onresize = function(){ 
var style = $('#button-selection').position(); 
if(style == "relative"){ 
$("#button-section").css("position"," "); 
}else if(style == "fixed"){ 
    $("#button-section").css("position","relative"); 
}    
}; 


window.onresize = function(){ 
      var style = $('#button-selection').css('position'); 
      if(style == "relative"){ 
       $("#button-section").css("position"," "); 
      }else if(style == "fixed"){ 
       $("#button-section").css("position","relative"); 
      }    
     }; 

樣式返回undefined。當文檔準備就緒時,我正在運行它。我試着用窗口準備好,但結果是一樣的。上述兩個方法都返回undefined!

+0

第二部分對我的作品如預期。看到這裏:http://jsfiddle.net/haZfH/ 也許你應該檢查什麼css('位置')實際輸出。也許問題出在CSS上。 – Chris 2013-04-11 08:04:55

+0

我會檢查它!理論上第二種方法應該工作! – 2013-04-11 08:08:50

回答

5

更改此:

var style = $('#button-selection').position(); 

這樣:

var style = $('#button-selection').css('position'); 

.position()用於獲取該元素的座標。

從文檔:

獲取匹配的元素,相對於偏移父的第一個元素的當前座標。


更新:

使用$(window).resize()來代替。我有一個測試的情況在這裏:in this fiddle.

$(window).resize(function() { 
    var style = $('button').css('position'); 
    if (style == "relative") { 
    alert('relative'); 
    } else if (style == "fixed") { 
    alert('fixed'); 
    } 
}); 
+0

我用那種方法,但結果是一樣的! – 2013-04-11 07:59:05

+0

@DimalChandrasiri剛剛更新了答案,並添加了小提琴鏈接。檢查並看看是否有幫助。 – Jai 2013-04-11 08:11:00

+0

我用你的方法,它的工作原理,但有一個錯誤,當我最小化或最大化屏幕時它會觸發兩次! – 2013-04-11 09:02:00

1

jQuery的文件說.POSITION()是:

說明:獲取的第一個元素的當前座標中 匹配的元素,相對於抵消父母。

你應該使用:腳本

var style = $('#button-selection').css('position');