滚动页面以便元素可见

pst*_*ton 8 javascript prototypejs

我刚刚尝试了原型的scrollTo函数,正如文档所述,它

滚动窗口,使元素显示在视口的顶部

我想要一个功能

  1. 如果元素在视口中不完全可见,则仅滚动
  2. 滚动以使元素出现在视口的中心

有没有人知道原型,scriptaculous或独立的这样的功能?

gbl*_*zex 6

我想你需要这样的东西(演示):

window.height

function getWindowHeight() {
  var body  = document.body;
  var docEl = document.documentElement;
  return window.innerHeight || 
         (docEl && docEl.clientHeight) ||
         (body  && body.clientHeight)  || 
         0;
}
Run Code Online (Sandbox Code Playgroud)

滚动

function scrollElemToCenter(id, duration) {
  var el = document.getElementById(id);
  var winHeight = getWindowHeight();
  var offsetTop = el.offsetTop;
  if (offsetTop > winHeight) { 
    var y = offsetTop - (winHeight-el.offsetHeight)/2;
    // wo animation: scrollTo(0, y);
    scrollToAnim(y, duration);
  }
}
Run Code Online (Sandbox Code Playgroud)

动画 (可选,你可以使用script.aculo.us等)

function interpolate(source,target,pos) { return (source+(target-source)*pos); }
function easing(pos) { return (-Math.cos(pos*Math.PI)/2) + 0.5; }

function scrollToAnim(targetTop, duration) {
  duration || (duration = 1000);
  var start    = +new Date,
      finish   = start + duration,
      startTop = getScrollRoot().scrollTop,
      interval = setInterval(function(){
        var now = +new Date, 
            pos = (now>finish) ? 1 : (now-start)/duration;
        var y = interpolate(startTop, targetTop, easing(pos)) >> 0;
        window.scrollTo(0, y);
        if(now > finish) { 
          clearInterval(interval);
        }
      }, 10);
}  
Run Code Online (Sandbox Code Playgroud)

得到滚动根

var getScrollRoot = (function() {
  var SCROLL_ROOT;
  return function() {
    if (!SCROLL_ROOT) {
      var bodyScrollTop  = document.body.scrollTop;
      var docElScrollTop = document.documentElement.scrollTop;
      window.scrollBy(0, 1);
      if (document.body.scrollTop != bodyScrollTop)
        (SCROLL_ROOT = document.body);
      else 
        (SCROLL_ROOT = document.documentElement);
      window.scrollBy(0, -1);
    }
    return SCROLL_ROOT;
  };
})();
Run Code Online (Sandbox Code Playgroud)