Javascript:目标特定的div或元素?

时间:2014-10-11 13:33:55

标签: javascript html scroll target

我想重写以下代码,以便它不会获得<body>的高度,而是我将对象放入执行函数的元素的高度:

var img = document.getElementById("logo");
window.onscroll = function() {
var bodyHeight = parseInt(getComputedStyle(document.body).height, 10);
var scrollLimit = bodyHeight - window.innerHeight;
var scrollTop = document.body.scrollTop;
var scrollPCT = (scrollTop / (scrollLimit / 100)) / 100;
logo.style.top = bodyHeight * scrollPCT - logo.offsetHeight + "px";
};

我如何定位ID,而不是document.body?我试过以下但是根本没有工作:

var img = document.getElementById("logo");
window.onscroll = function() {
var body = document.getElementById("container");
var bodyHeight = parseInt(getComputedStyle(document.getElementById("container")).height, 10);
var scrollLimit = bodyHeight - window.innerHeight;
var scrollTop = document.getElementById("container").scrollTop;
var scrollPCT = (scrollTop / (scrollLimit / 100)) / 100;
logo.style.top = bodyHeight * scrollPCT - logo.offsetHeight + "px";
};

所需的效果包括反向滚动,其中图像将在用户向下滚动时向下移动,而不是像往常一样向上移动。

1 个答案:

答案 0 :(得分:1)

我猜计算出的高度不起作用?使用clientHeight属性:

var bodyHeight = document.getElementById("container").clientHeight;

(或其中一个other height properties