将内部div的宽度设置为容器的宽度

时间:2016-02-08 23:58:51

标签: javascript jquery html css twitter-bootstrap

我正在尝试修改bootstrap css,我希望.dropdown-menu扩展到容器的整个宽度,但设置width:100%会将宽度设置为父宽度。我尝试使用jquery,这有效,但随着菜单增加,它们不适合容器。我如何解决这个问题,使每个下拉菜单具有相同的宽度,从左到右适合整个容器?的 jsfiddle

jquery

$(window).bind("load resize", function(){
$('.extend').width($('.container').width());
});

html

<div class="container">

  <!-- Static navbar -->
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu extend">
              <li><a href="#">Action</a></li>
              <li><a href="#">Another action</a></li>
              <li><a href="#">Something else here</a></li>
              <li role="separator" class="divider"></li>
              <li class="dropdown-header">Nav header</li>
              <li><a href="#">Separated link</a></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu extend">
              <li><a href="#">Action</a></li>
              <li><a href="#">Another action</a></li>
              <li><a href="#">Something else here</a></li>
              <li role="separator" class="divider"></li>
              <li class="dropdown-header">Nav header</li>
              <li><a href="#">Separated link</a></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
        </ul>
      </div><!--/.nav-collapse -->
    </div><!--/.container-fluid -->
  </nav>

</div> <!-- /container -->

1 个答案:

答案 0 :(得分:2)

$(window).bind("load resize", function(){
    adjust();
 $('.extend').width($('.container').width());
});

function adjust(){
$('.dropdown-toggle').each(function(){
var left = ($('body').width()-$('.container').width())/2;
  $(this).parent().find('.dropdown-menu').css('margin-left','-'+($(this).offset().left-left)+'px');
 });
}
adjust();

请试一试。这是工作fiddle