2009-12-09 143 views
2

我做了if函數來檢查寬度是否爲< 100px。由於某種原因,它隱藏了一切。有人知道爲什麼jQuery獲取高度和寬度

$(document).ready(function() { 
var pic = $(".pic"); 

// need to remove these in of case img-element has set width and height 
$(".pic").each(function() { 
    var $this = $(this); 
    $this.removeAttr("width"); 
    $this.removeAttr("height"); 

    var pic_real_width = $this.width(); 
    var pic_real_height = $this.height(); 
    if(pic_real_width<100){ 
    $(this).css("display","none"); 
    } 
    }); 

}); 

回答

3

試試這個:

$(document).ready(function() { 
    $(".pic").each(function() { 
     var pic = $(this); 
     pic.removeAttr("width"); 
     pic.removeAttr("height"); 

     var pic_real_width = pic.width(); 
     var pic_real_height = pic.height(); 
     alert(pic_real_width); 
    }); 
}); 
+0

它的工作,謝謝。 var pic_real_width = $ this.width(); var pic_real_height = $ this.height();如果(pic_real_width <100){ \t $(「。pic」).css(「display」,「none」); \t} 隱藏所有圖像。任何ideea爲什麼它不適用於特定的條件? – Carvefx 2009-12-09 12:13:27

+0

請參閱我對您最新問題的回答:http://stackoverflow.com/questions/1873536/jquery-height-condition/1873546#1873546 我已經在那裏回答您。 – 2009-12-09 12:19:31

4

您使用pic時,你應該使用$(this)

$(".pic").each(function() { 
    var $this = $(this); 
    $this.removeAttr("width"); 
    $this.removeAttr("height"); 

    var pic_real_width = $this.width(); 
    var pic_real_height = $this.height(); 
    alert(pic_real_width); 
    }); 

你也應該留意是否被調整與CSS的圖像。取而代之的

$this.removeAttr("width"); 
    $this.removeAttr("height"); 

嘗試

$this.css({width: 'auto', height: 'auto'}); 
1

我想盡解決方案,在這裏,但沒有爲我工作,所以我創建了自己的腳本,它的工作原理包括IE在內的所有瀏覽器。下面我的腳本:

$(function(){ 
var sbar = $(".sidebar").outerHeight(true); 
var pcont = $(".post_content").outerHeight(true); 
if(sbar < pcont){ 
    $(".sidebar").css("min-height",pcont+"px"); 
} 
}); 

/*** CSS ***/ 

.sidebar{ 
    float:left; 
    min-height: 500px; 
    width:180px; 
} 

.post_content{ 
    float:left; 
    min-height: 500px; 
    width:593px; 
} 

我希望這也能與你一起工作!

1
$this.css({width: 'auto', height: 'auto'}); 

嘗試