jQuery得到高度&宽度

时间:2009-12-09 11:53:23

标签: javascript jquery css image

我做了一个if函数来检查宽度是否为< 100px的。出于某种原因,它隐藏了一切。谁知道为什么?

$(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");
    }
    });

 });

4 个答案:

答案 0 :(得分: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 :(得分: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);
    });
});

答案 2 :(得分: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;
}

我希望这也适合你!

答案 3 :(得分:1)

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

试试吧