在javascript中实现固定位置滚动时会导致Safari抖动 [英] Implementing fixed position in javascript causes jitter in Safari when scrolling

查看:648
本文介绍了在javascript中实现固定位置滚动时会导致Safari抖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

固定位置在我的用例中不起作用,因为它固定在浏览器窗口上,并且您可能处于文本不在屏幕右侧且无法进入的状态.无论如何,我尝试使用绝对定位,然后在javascript中调整顶部".在Firefox和Chrome浏览器中效果很好,但是在Safari中,滚动时内容会抖动.

Fixed position does not work for my use case because it is fixed to the browser window and you can get in a state where the text is off your screen to the right and you can not get to it. Anyways, I have attempted to use absolute positioning and then adjusting the "top" in javascript. It works pretty well in firefox and Chrome, but in Safari the content jitters when you scroll.

http://jsfiddle.net/Z8UFE/4/

<div class="fixed sticky" data-offset-top="50"><p>fixed</p></div> 

$(document).ready(function() {
    var documentHeight = $(document).height();
    $(document).scroll(function() {
      var scrollTop = $(window).scrollTop();

      $(".sticky").offset(function() {
        $this = $(this);
        var offsetTop = $this.data("offset-top");

        if (scrollTop < 0) {
          scrollTop = 0;
        }

        var newTop = offsetTop + scrollTop;
        if (newTop < offsetTop) {
          newTop = offsetTop;
        }

        // Prevents document from infinitely expanding.
        var maxTop = documentHeight - $this.height();
        if (newTop > maxTop) {
          newTop = maxTop
        }

        // Prevents a bit of jitter since the current offset can be
        // not precisely the initial offset. 338 Vs. 338.12931923
        var currentTop = $this.offset().top;
        if ( Math.abs(currentTop - newTop) >= 1 ) {
          return { top: newTop }
        } else {
          return {}
        }
      });
    });
})

推荐答案

我想我了解您要实现的目标.

I think I understand what you are trying to achieve.

如果您在元素上保持固定位置并使用javascript/jquery将其水平重新放置,则可以保持平滑的垂直滚动并允许它也保持其水平位置:

If you keep the fixed positioning on the element and reposition it horizontally with javascript/jquery you can keep the smooth vertical scrolling and allow it to also keep its horizontal positioning:

$(function() {
    var $sticky = $('.sticky');
    var target  = 800;

    $(document).scroll(function() {
        var left = $(window).scrollLeft();
        var adj  = target - left;
        $sticky.css({left: adj});
    });
});

这使用 scrollLeft(),它是scrollTop()的水平对等物

This uses scrollLeft() which is the horizontal counterpart to scrollTop()

http://jsfiddle.net/Z8UFE/18/

这篇关于在javascript中实现固定位置滚动时会导致Safari抖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆