iOS Safari 问题 - 将绝对位置更改为固定位置时滚动时元素变得不可见

iOS Safari issue - Element becomes invisible while scrolling when changing position absolute to fixed

我想使用页面上的一个元素作为以下内容的标题,但是当用户滚动到内容中时,这个 title-element 应该固定在 header。类似于iOS中的ABC-captions music-app.

看这里:https://jsfiddle.net/1e7ync4w/

HTML

<div>
  <div class="top">
  Test
  </div>
  <div class="content">
    <div class="scroller">

    </div>

    Test
  </div>
</div>

CSS

.top {
  background-color: yellow;

  height: 300px;
}

.content {
  position: relative;

  height: 600px;

  background-color: green;
}

.scroller {
  position: absolute;

  width: 100%;
  height: 10px;

  top: 0;
  left: 0;

  background-color: blue;
}

.scroller.fixed {
  position: fixed;
}

JS

$(document).ready(function() {
    $(window).on('scroll touchmove', function() {
      $('.scroller').removeClass('fixed');


    var scrollTop = $(window).scrollTop();
    var scrollerOffsetTop = $('.scroller').offset().top;

    if(scrollerOffsetTop <= scrollTop) {
                $('.scroller').addClass('fixed');
    }
});
  });

问题是 iOS safari 似乎有一个错误,在滚动时将元素更改为固定(通过 JavaScript)。一旦用户滚动到内容中,title-element 就会变得不可见,但在从显示屏上松开手指后会显示 (scroll-end)。

我只在 iOS 9.3.2 safari 上测试过这个问题,但我认为这个问题比较老。

我找到了解决这个问题的方法。这有点老套,但这是我为这个 iOS-bug 找到的唯一解决方法。

浏览器的 GPU 需要 "activated" 才能更新相应的元素。这可以通过在定位跳转到固定后立即通过 JS 设置 transform: translate 样式来实现。

示例代码如下所示:

$(document).ready(function () {
    $(window).on('scroll touchmove', function () {
        $('.scroller').removeClass('fixed');


        var scrollTop = $(window).scrollTop();
        var scrollerOffsetTop = $('.scroller').offset().top;

        if (scrollerOffsetTop <= scrollTop) {
            $('.scroller').addClass('fixed').css({
                'transform': 'translate3d(0px,0px,0px)',
                '-moz-transform': 'translate3d(0px,0px,0px)',
                '-ms-transform': 'translate3d(0px,0px,0px)',
                '-o-transform': 'translate3d(0px,0px,0px)',
                '-webkit-transform': 'translate3d(0px,0px,0px)'
            });
        }
    });
});