代码之家  ›  专栏  ›  技术社区  ›  Pons Purushothaman

通过jQuery应用时出现“width”问题

  •  4
  • Pons Purushothaman  · 技术社区  · 6 年前

    我有一个容器DIV,其中有7个DIV(这是可变的数字)对齐为7列。因为列的数量是不同的,所以我想采用列计数并使用jquery计算(100/列计数)并将此宽度应用于每个列列。用于对于每一列的分隔,除了最后一列外,我都对其他列应用了2px的右边框。我还应用了边框框大小调整,以避免百分比宽度之间的冲突和像素宽度边框。

    我的问题是当通过jquery width应用列宽时,

    var count = $('.col').length;
    $('.col').width(100/count+'%');
    

    前6列的宽度似乎为“16.2857%”,最后一列的宽度为“14.2857%”。实际上,14.2857是要应用的正确值。边框和框大小属性会影响它。

    var count = $('.col').length;
    $('.col').css('width',100/count+'%');
    

    下面是我的工作样本

    $(window).ready(function(){
    
      //This make the width Issue
      var count = $('.col').length;
      $('.col').width(100/count+'%');
      
      //But This works perfectly fine
      //var count = $('.col').length;
      //$('.col').css('width',100/count+'%');
    });
    .container{
      width: 210px;
      height:120px;
      float: left;
      border: solid 2px red;
    }
    .col{
      height: 100%;
      float:left;
      background:green;
      border-right: solid 2px yellow;
      box-sizing: border-box;
    }
    .col:last-child{
      border-right: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
    </div>
    2 回复  |  直到 6 年前
        1
  •  2
  •   Mamun    6 年前

    .width()

    请注意,.width()将始终返回内容宽度,而不考虑CSS box size属性的值。从jquery1.8开始,这可能需要检索CSS width plus box size属性,然后在元素具有box size:border box时减去每个元素上的任何潜在边框和填充。为了避免这种损失,请使用.css(“width”)而不是.width()。

    尽管首选的方法是 .css() outerWidth() 而不是 width()

    $(window).ready(function(){
    
      //This make the width Issue
      var count = $('.col').length;
      $('.col').outerWidth(100/count+'%');
      //But This works perfectly fine
      //var count = $('.col').length;
      //$('.col').css('width',100/count+'%');
    });
    .container{
      width: 210px;
      height:120px;
      float: left;
      border: solid 2px red;
    }
    .col{
      height: 100%;
      float:left;
      background:green;
      border-right: solid 2px yellow;
      box-sizing: border-box;
    }
    .col:last-child{
      border-right: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
    </div>
        2
  •  2
  •   4b0 Agit    6 年前

    看起来这与jQuery文档中的这一行有关

    请注意,.width()将始终返回内容宽度,无论 需要检索CSS width plus box size属性,然后 当 元素具有框大小:边框框。要避免这种惩罚,请使用.css( “width”)而不是.width()

    https://api.jquery.com/width/