使用Prototype滚动窗口沿y轴居中?

时间:2014-06-06 11:14:48

标签: javascript prototypejs

我有一个元素,我想沿着y轴放在屏幕的中心。这就是我到目前为止所做的:

window.scrollTo(0, (document.viewport.getHeight() / 2) - $$('.my-elems-class')[0].getHeight());

事情是,它在不同屏幕上的不同位置。怎么会这样?

感谢fpr帮助!

1 个答案:

答案 0 :(得分:2)

x轴为0; 因为y轴是一半。试试这个

var element_top = $$('.my-elems-class:first').offset().top;

var documentHeight = window.innerHeight;
documentHeight = documentHeight ? documentHeight : Math.min(document.documentElement.clientHeight, document.body.clientHeight);

var y_axis = element_top - (documentHeight/2);

所以现在使用

window.scrollTo(0, y_axis);