Implementing fixed position in javascript causes j

2019-05-01 04:47发布

问题:

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 {}
        }
      });
    });
})

回答1:

I think I understand what you are trying to achieve.

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});
    });
});

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

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