我试图在body的scrollTop大于其offsetTop之后才设置div。我的解决方案在Chrome上运行得很完美,但Firefox似乎没有响应,也没有任何错误。
我的代码:
var sticky = document.createElement('div');
sticky.style.width = "300px";
sticky.style.height = "600px";
sticky.style.backgroundColor = "red";
document.querySelector('*[id^="channel."]').parentElement.appendChild(sticky);
var sticky_offset = sticky.offsetTop;
function makeItStick() {
if (document.body.scrollTop > sticky_offset) {
sticky.style.position = "fixed";
sticky.style.top = "0px";
} else {
sticky.style.position = "";
}
};
window.addEventListener("scroll", makeItStick);