【问题标题】:jQuery get height & widthjQuery获取高度和宽度
【发布时间】:2009-12-09 11:53:23
【问题描述】:

我创建了一个if 函数来检查宽度是否小于 100 像素。由于某种原因,它隐藏了一切。有人知道为什么吗?

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

 });

【问题讨论】:

    标签: javascript jquery css image


    【解决方案1】:

    当你应该使用$(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);
         });
    

    您还应该注意使用 CSS 调整大小的图像。

    代替

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

    试试

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

      【解决方案3】:

      我在这里尝试了所有解决方案,但没有一个对我有用,所以我创建了自己的脚本,它适用于包括 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;
      }
      

      我希望这对你也有用!

      【讨论】:

        【解决方案4】:
        $this.css({width: 'auto', height: 'auto'});
        

        试试看

        【讨论】:

          猜你喜欢
          • 2016-03-25
          • 1970-01-01
          • 2017-02-28
          • 2017-12-26
          • 2012-04-04
          • 2012-10-10
          • 2021-06-30
          • 2010-11-18
          • 1970-01-01
          相关资源
          最近更新 更多