我有一个简单的页面,我想在向下滚动时固定顶部的 div,并设置一个“To Top”div 返回页面顶部。我使用 document.documentElement.scrollTop 获取当前从顶部滚动的位置,并使用 document.documentElement.onscroll
调用该函数。但是当我设置“到顶部”div 时,我不得不使用 window.scrollTo(0,0)
函数返回到页面顶部,因为 document.documentElement.scrollTo( 0,0)
无效。 window
和 document.documentElement
有什么区别?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>scroll demo</title>
<style>
#heading {
color: white;
background:steelblue;
position:absolute;
left:10px;
top:-20px;
padding:5px;
}
p {
color: green;
}
span {
color: red;
display: none;
}
#top{
padding:5px;
border:dotted 2px steelblue;
box-shadow: -3px -3px 3px;
background:steelblue;
width:75px;
position:fixed;
right:0;
bottom:0;
display:none;
opacity:0.9;
border-top-right-radius:100%;
border-top-left-radius:100%;
}
</style>
</head>
<body>
<div id="heading"><h1>Try scrolling the iframe.</h1></div>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<div onclick="top_function()" id="top">
<h3>To Top</h3>
</div>
<script>
document.documentElement.onscroll = function(){ //a function is call when scroll using .onscroll
var x = document.documentElement.scrollTop; //x is the current scroll position of document
if(x > 0){ //set greater than zero to avoid the annoytingblinking effect
document.getElementById("heading").style.position="fixed";
document.getElementById("heading").style.top="-20px";
document.getElementById("heading").style.left="10px";
}
else{
document.getElementById("heading").style.position="absolute";
document.getElementById("heading").style.top="-20px";
document.getElementById("heading").style.left="10px";
};
if(x > 100){
document.getElementById("top").style.display="inline-block";
}
else{
document.getElementById("top").style.display="none";
};
}; //ends function onscroll
function top_function(){
window.scrollTo(0,0);
};
最佳答案
一般来说,DOM API 很难。根据您的工作,jQuery 有可能在可理解性、可读性、可维护性和跨平台兼容性方面为您的开发带来更多 yield 。
也就是说,document.documentElement
是对 <HTML/>
的引用文档的节点。除非发生了非常奇怪的事情(例如 html { overflow: scroll; }
),否则 scrollTop
对于 <HTML/>
应始终为 0
就像其他不滚动的节点一样。
直接页面滚动实际上发生在 window
上. This fiddle显示了如何监听窗口上的滚动偏移量变化,获取窗口的当前滚动偏移量,并将窗口滚动到新的偏移量。
郑重声明,如果您想创建一个滚动到页面顶部的链接,则根本不需要 JavaScript,只需创建一个指向 #
的链接即可。 .只要您不拦截链接的 native 处理,定义的行为就是滚动回页面顶部。
关于javascript - Window 与 document.documentElement 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30651251/