【发布时间】:2022-02-05 00:36:05
【问题描述】:
我有一个简单的页面,我想在向下滚动时固定顶部 div,并让“To Top” div 返回页面顶部。我使用 document.documentElement.scrollTop 来获取我当前从顶部滚动的位置,并使用document.documentElement.onscroll 来调用该函数。但是当我设置“To Top” 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);
};
【问题讨论】:
-
“最佳实践”问题往往会以基于意见的方式结束。您可能应该将那部分省略或定义您需要“最佳”的含义(例如“哪个更快?”)
标签: javascript scrolltop onscroll