位置:粘滞半路?

时间:2017-10-06 10:51:38

标签: css3

我有一个添加了position: sticky的侧边栏,但是当我滚动到某个点时它会停止粘贴?!

在Chrome版本中测试:版本61.0.3163.100和Safari版本:11.0

HTML:

<div class="sticky">
  this should stick!
</div>

<div class="content">
  this is content
</div>

CSS:

<style media="screen">
  .sticky {
    background-color: #ccc;
    position: -webkit-sticky;
    position: -moz-sticky;
    position: -ms-sticky;
    position: -o-sticky;
    position: sticky;
    top: 15px;
    width: 100px;
    float: left;
  }

  .content{
    background-color: #eee;
    height: 3000px;
    width: 700px;
    float: right;
  }
</style>

3 个答案:

答案 0 :(得分:2)

大多数浏览器http://caniuse.com/#feat=css-sticky

不支持

position: sticky;

您可以尝试这样的事情:

<强> HTML

<div class="sticky-block">
  this should stick!
</div>

<强> CSS

.sticky {
   position: fixed;
   top: 15px;
}

<强> JS

var $stickyBlock = document.querySelector('.sticky-block');
var origOffsetY = $stickyBlock.offsetTop - 15; // 15 is your top margin

function onScroll() {
    window.scrollY >= origOffsetY ? $stickyBlock.classList.add('sticky') :
    $stickyBlock.classList.remove('sticky');
}

document.addEventListener('scroll', onScroll);

jQuery

var $stickyBlock = $('.sticky-block');
var origOffsetY = $stickyBlock.offset().top - 15;  // 15 is your top margin

function onScroll() {
    window.scrollY >= origOffsetY ? $stickyBlock.addClass('sticky') :
    $stickyBlock.removeClass('sticky');
}

$(document).on('scroll', onScroll);

jsfiddle

答案 1 :(得分:2)

在这里,试试这个,我会说它更好,而不是使用“粘性”,它不使用Jquery或任何简单的位置固定。

HTML

<div class="sticky">
  this should stick!
</div>

<div class="content">
  this is content
</div>

的CSS

.sticky {
    background-color: #ccc;
    top: 15px;
    width: 100px;
    float: left;
    position:fixed;
  }

  .content{
    background-color: #eee;
    height: 3000px;
    width: 700px;
    float: right;
  }

https://jsfiddle.net/udxuh1qf/

答案 2 :(得分:0)

我在jsfiddle上测试了你的代码,在这里,它可能是你的屏幕媒体查询导致你的问题。看看我的粘贴版本。我希望它能解决你的问题。

&#13;
&#13;
      .sticky {
      background-color: #ccc;
      color:red;
      position: sticky;/* required */
      position: -webkit-sticky;/* required */
      top: 15px; /* required */
      float:left;
      }

      .content{
        background-color: #eee;
        height: 3000px;
        width: 700px;
        float right;
      } 
&#13;
    <div class="sticky">
      this should stick!
    </div>

    <div class="content">
      this is content
    </div>
&#13;
&#13;
&#13;