admin管理员组

文章数量:1290956

I made an if function to check if the width is < 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");
    }
    });

 });

I made an if function to check if the width is < 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");
    }
    });

 });
Share Improve this question edited Dec 9, 2011 at 22:56 cmcginty 117k44 gold badges170 silver badges164 bronze badges asked Dec 9, 2009 at 11:53 CarvefxCarvefx 4481 gold badge5 silver badges18 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4

You're using pic when you should be using $(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);
     });

You should also watch for images that are resized with 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. 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'});

try it

本文标签: javascriptjQuery get height amp widthStack Overflow