当我点击每个链接时,我有三个div,一个菜单和三个链接;页面滚动到相关的div,顶部的div丰富到页面顶部。 如何在屏幕顶部和顶部之间设置40px的距离? 这是我的代码:
<html>
<head>
<style>
#menu{width:100%;height:40px;background:yellow;position:fixed}
#menu ul li{display:inline;padding:10px}
#top, #middle, #bottom{height:800px;border-top:1px solid}
</style>
<script>
window.smoothScroll = function(target) {
var scrollContainer = target;
do { //find scroll container
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 10;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do { //find the top of target relatively to the container
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
scroll = function(c, a, b, i) {
i++; if (i > 30) return;
c.scrollTop = a + (b - a) / 30 * i;
setTimeout(function(){ scroll(c, a, b, i); }, 20);
}
// start scrolling
scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}
</script>
</head>
<body>
<div id="menu">
<ul>
<li>
<a onclick="smoothScroll(document.getElementById('top'))">Top</a>
</li>
<li>
<a onclick="smoothScroll(document.getElementById('middle'))">Middle</a>
</li>
<li>
<a onclick="smoothScroll(document.getElementById('bottom'))">Bottom</a>
</li>
</ul>
</div>
<div id="top"><h1>Top</h1></div>
<div id="middle"><h1>Middle</h1></div>
<div id="bottom"><h1>Bottom</h1></div>
</body>
</html>
我不想在菜单之前隐藏h1。
答案 0 :(得分:1)
计算滚动目标时需要测量顶部条形高度。
// get topbar height to offset the scroll taget coords
var topbarHeight = document.getElementById("menu").offsetHeight;
// apply scroll offset
targetY -= topbarHeight;
答案 1 :(得分:0)
您可以在div中添加一些填充:
#top, #middle, #bottom{height:500px;border-top:1px solid; padding-top: 30px}