我需要类似的内容,但position:absolute而不是fixed

用户滚动页面时,JavaScript是否可以更改顶部?



      var elementPosition = $('#div2').offset();
      var div1 = $('#div1');
      var main=$('#main');
      var spacer = $('#spacer');

  $(window).scroll(function(){
          if($(window).scrollTop() > elementPosition.top){
          		var left = Math.ceil(div1.offset().left + div1.outerWidth()) + 'px';
					console.log(main.width(), div1.width())
              var width = main.width()  - div1.outerWidth() + 'px';
                $('#div2').css({
                	position: 'fixed',
                  left: left,
                  width: width
                });

          } else {
              $('#div2').css({
              	'position':'static',
                width: 'auto'
              });

          }
  });

body{
  margin: 0;
  width: 100%;
}
* { box-sizing: border-box;}
#main{
  width:80%;
  margin:0 auto;
}
#div1{
  width: 10%;
  border: solid 1px #000000;
  background-color: #0066CC;
  float: left;
}
#div2{
  height: 30px;
  border: solid 1px #000000;
  background-color: #66CC00;
}
#spacer {
  width: 90%;
  min-height:30px;
  float:left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="main">
    <div id="div1">Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor. Pellentesque facilisis. Nulla imperdiet sit amet magna. Vestibulum dapibus, mauris nec malesuada fames ac turpis velit, rhoncus eu, luctus et interdum adipiscing wisi. Aliquam erat ac ipsum. Integer aliquam purus. Quisque lorem tortor fringilla sed, vestibulum id, eleifend justo vel bibendum sapien massa ac turpis faucibus orci luctus non, consectetuer lobortis quis, varius in, purus. Integer ultrices posuere cubilia Curae, Nulla ipsum dolor lacus, suscipit adipiscing. Cum sociis natoque penatibus et ultrices volutpat. Nullam wisi ultricies a, gravida vitae, dapibus risus ante sodales lectus blandit eu, tempor diam pede cursus vitae, ultricies eu, faucibus quis, porttitor eros cursus lectus, pellentesque eget, bibendum a, gravida ullamcorper quam. Nullam viverra consectetuer. Quisque cursus et, porttitor risus. Aliquam sem. In hendrerit nulla quam nunc, accumsan congue. Lorem ipsum primis in nibh vel risus. Sed vel lectus. Ut sagittis, ipsum dolor quam.</div>
    <div id="spacer">
     <div id="div2">div2</div>
    </div>

  </div>
</body>

最佳答案

更改为this

$('#div2').css({
  position: 'absolute',
  top: $(window).scrollTop(),
  left: left,
  width: width
});


代替(上一个):

$('#div2').css({
  position: 'fixed',
  left: left,
  width: width
});

关于javascript - div固定,但position:absolute,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38144323/

10-12 03:04