固定位置-将宽度设置为等于容器

Position Fixed - Set width to be equal to container

本文关键字:设置 于容器 定位 位置      更新时间:2024-06-24

我一直试图在用户滚动足够远时将div的位置设置为固定。我注意到,当div的位置设置为固定时,宽度与父元素的宽度不同。如何保持position:fixed的div的宽度与父元素的宽度相同?

在这个例子中,一旦设置了position:fixed,我希望底部div的宽度与黄色框的宽度相同。

http://jsfiddle.net/BYJPB/

这是我的HTML:

<header>
  <div class="filler-space">
    Filler Space
  </div>
  <div class="toolbar">
    <div class="current-article">
        <div class="progress-bar"></div>
        My article
    </div>
  </div>
</header>

这是我的CSS:

body {
  padding:0 10px;
  height: 1000px;
}
.filler-space {
  background-color: yellow;
  border:1px solid #000000;
  height: 140px;
}
.toolbar {
  border: 1px solid black;
}
.current-article {
  font-weight: 600;
  height: 100%;
  line-height: 40px;
  overflow: hidden;
  width: 100%;
  z-index: -1;
}
.progress-bar {
  position: absolute;
}
.prog .progress-bar {
  background: none repeat scroll 0 0 #F2F4F7;
  bottom: 0;
  height: 100%;
  left: 0;
  margin: 0 -10px 0 -10px;
  overflow: hidden;
  right: 0;
  top: 0;
  transition: width 0.1s ease 0s;
  z-index: -1;
  width: 100%;
}

这是我的JavaScript:

var $toolbar = $('.toolbar');
var $window = $(window);
var $header = $('header');
$(document).scroll(function() {
  var scrollTop = $window.scrollTop();
  if ( scrollTop > 150) {
    $toolbar.css({
        'position' : 'fixed',
        'top' : 0
    });
    $header.addClass('prog');
  }
  else {
    $toolbar.css({
        'position' : 'static',
        'top' : 0
    });
    $header.removeClass('prog');
  }
});

更新你的js,我不理解你的要求,但我认为这就是你想要的。

if ( scrollTop > 150) {
    $toolbar.css({
        'position' : 'fixed',
        'top' : 0,
        'width':$header.width()
    });
    $header.addClass('prog');
}
else {
    $toolbar.css({
        'position' : 'static',
        'top' : 0
    });
    $header.removeClass('prog');
}