简体   繁体   English

jQuery获取高度和宽度

[英]jQuery get height & width

I made an if function to check if the width is < 100px. 我做了一个if函数来检查宽度是否小于100px。 For some reason it hides everything. 出于某种原因,它隐藏了一切。 Anyone know why? 谁知道为什么?

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

 });

You're using pic when you should be using $(this) : 当你应该使用$(this)时,你正在使用pic

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

You should also watch for images that are resized with CSS. 您还应该观察使用CSS调整大小的图像。

Instead of 代替

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

try 尝试

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

Try this: 尝试这个:

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

I tried every solutions here but none worked for me so I created my own script and it works in all browsers including IE. 我在这里尝试了所有解决方案,但没有一个适合我,所以我创建了自己的脚本,它适用于所有浏览器,包括IE。 Heres my script: 继承我的剧本:

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

I hope this will work with you too!! 我希望这也适合你!

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

试试吧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM