div保持固定在某一点上

时间:2014-11-18 20:14:30

标签: javascript html css

有一个div,样式从顶部固定60px。我希望当我向下滚动并且div从顶部的距离达到10px时,div会在其余的滚动时停止,当我向上滚动时它会从顶部回到旧式60px。我做了很多搜索,但我没有找到这样的东西。但是有一个代码可以计算距离顶部的距离:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

2 个答案:

答案 0 :(得分:0)

这是使用纯JavaScript进行此操作的一种方法。如果您愿意,可以使用document.getElementById之类的jQuery选择器替换$("id")之类的选择器。



window.onscroll = function(){
  var el = document.getElementById('sticky'),
      s = window.pageYOffset || document.documentElement.scrollTop, // how much page is scrolled
      t = document.getElementById('main').getBoundingClientRect().top; // top of main div
  
  if(s > t){
    el.style.position = 'fixed'; //make position fixed instead of absolute
  }else{
    el.style.position = ''; //clear styles if back to original position
  }
}

body { 
  min-height: 200em; 
  margin: 0;
  padding: 0;
}

header {
  background: black;
  color: white;
  padding: .5em;
}

#main { position: relative; } /* important so the sticky box positions relative to this */

#sticky {
    background: cornflowerblue;
    padding: .5em;
    position: absolute;
    right: 1em;
    top: 1em;
    width: 10em;
    color: white;
}

<header>This is just a page header or toolbar.</header>

<section id="main">
  <div id="sticky">This should stick to the top when scrolled.</div>
</section>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是一个jQuery解决方案。如果我们从页面顶部开始超过10px,则为该元素添加一个is-sticky类,然后您可以使用CSS设置样式。

// store the element in a variable
var element = $('.item'),
    visible = false;

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

  /**
   * store the scroll distance in px
   * from the top of the viewport
   */
  var scroll = $(window).scrollTop();

  /**
   * if the scroll is greater than or equal
   * to 10px add a class of .is-sticky to the element
   * otherwise we're less than 10px from the top
   * of the document and therefore don't want
   * the element to have the .is-sticky class
   */
  if(scroll >= 10) {
    if(!visible) {
      element.addClass('is-sticky');
      visible = true;
    }
  } else {
    if(visible) {
      element.removeClass('is-sticky');
      visible = false;
    }
  }
});