如何在滚动过去后使div内的元素变粘?

时间:2014-12-28 03:37:01

标签: jquery css sticky

如何制作,以便当用户滚动关闭按钮“关闭”时,它会卡在页面顶部?

我希望它与窗口右侧对齐(右:0px)并且'close'包含在div'容器'中,其宽度为500px,并以margin:auto为中心。 / p>

我试过这样做,当你滚过元素时,它会添加一个'sticky'类,它有一个位置:fixed。这似乎不起作用。

jsFiddle:http://jsfiddle.net/7j18fwpa/

jQuery的:

var top = $('.close').offset().top;
$(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top)
        $('.close').addClass('sticky');
    else
        $('.close').removeClass('sticky');
            $('.close').width($('.close').parent().width());
});

2 个答案:

答案 0 :(得分:2)

在您的情况下,您尝试使绝对定位元素相对于其容器变粘。

我把你的jsfiddle变成了这个:
http://jsfiddle.net/7j18fwpa/3/

所以你会:

HTML:

<div class="container">
    <div class="close sticky">CLOSE</div>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut dui nisi. Morbi cursus nibh eget imperdiet gravida. Etiam ultricies lectus quis mollis mattis. Quisque at tincidunt nisl, ut commodo turpis. Sed dapibus mi porta, tempor metus et, luctus mi. Donec hendrerit odio at augue mollis interdum. Vestibulum efficitur metus eget diam tempor egestas. Maecenas sit amet urna consectetur, ultrices tortor sit amet, convallis odio. Phasellus ut ante luctus, elementum est consequat, cursus velit. Phasellus eleifend massa in tellus sagittis, id viverra risus efficitur. Fusce auctor a nisi in mollis. Cras auctor ullamcorper consectetur. Nunc imperdiet feugiat nulla non tincidunt. Praesent pulvinar ut lacus sit amet sagittis. Sed et elit in ipsum elementum lobortis.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sed volutpat enim, sit amet varius elit. Sed vel diam consequat, lobortis diam vitae, aliquet diam. Morbi eget erat metus. Cras eget sollicitudin velit, eu cursus erat. Sed placerat, magna vitae feugiat rhoncus, ex turpis varius magna, nec laoreet nulla magna ac eros. Curabitur ut sollicitudin nibh. Proin et accumsan eros.</p>
</div>

CSS:

.container{
    width: 500px;
    height: 500px;
    background: red;
    margin: auto;
    position:relative;
}

.close{
    background: blue;
    width: 50px;
    height: 20px;
    position: absolute;
    right:0;
    top:100px;
}

JS:

$(function(){ // document ready

  if (!!$('.sticky').offset()) { // make sure ".sticky" element exists

    var containerTopOffset = $('.container').offset().top; // get offset the container
    var stickyTopOffset = $('.sticky').offset().top; // get offset of the sticky element
    var stickyTopCss = parseInt($('.sticky').css('top'), 10); // get original top pixels set on the sticky element from css

    $(window).scroll(function(){ // scroll event
      var windowTop = $(window).scrollTop(); // returns number 
      if (stickyTopOffset < windowTop){
        $('.sticky').css({ top: (windowTop-containerTopOffset) }); // set new top value for the sticky element that would be the window offset minus the container's offset
      } else {
        $('.sticky').css({ top: stickyTopCss }); // restore the original top value of the sticky element
      }
    });

  }

});

答案 1 :(得分:1)

$(function() { // document ready

  if (!!$('.close').offset()) { // make sure ".sticky" element exists

    var stickyTop = $('.close').offset().top; // returns number 

    $(window).scroll(function() { // scroll event

      var windowTop = $(window).scrollTop(); // returns number 

      if (stickyTop < windowTop) {
        $('.close').css({
          position: 'fixed',
          top: 0
        });
      } else {
        $('.close').css({
          position: 'absolute',
          top: '100px'
        });
      }

    });

  }

});
.container {
  width: 500px;
  height: 1000px;
  background: red;
  margin: auto;
  position: relative;
}
.close {
  background: blue;
  width: 50px;
  height: 20px;
  position: absolute;
  right: 0px;
  top: 100px;
}
.sticky {
  position: fixed;
  top: 0px;
}
<div class="container">
  <div class="close">CLOSE</div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut dui nisi. Morbi cursus nibh eget imperdiet gravida. Etiam ultricies lectus quis mollis mattis. Quisque at tincidunt nisl, ut commodo turpis. Sed dapibus mi porta, tempor metus et, luctus
    mi. Donec hendrerit odio at augue mollis interdum. Vestibulum efficitur metus eget diam tempor egestas. Maecenas sit amet urna consectetur, ultrices tortor sit amet, convallis odio. Phasellus ut ante luctus, elementum est consequat, cursus velit.
    Phasellus eleifend massa in tellus sagittis, id viverra risus efficitur. Fusce auctor a nisi in mollis. Cras auctor ullamcorper consectetur. Nunc imperdiet feugiat nulla non tincidunt. Praesent pulvinar ut lacus sit amet sagittis. Sed et elit in ipsum
    elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sed volutpat enim, sit amet varius elit. Sed vel diam consequat, lobortis diam vitae, aliquet diam. Morbi eget erat metus. Cras eget sollicitudin velit, eu cursus
    erat. Sed placerat, magna vitae feugiat rhoncus, ex turpis varius magna, nec laoreet nulla magna ac eros. Curabitur ut sollicitudin nibh. Proin et accumsan eros.</p>
</div>