我刚开始一个新网站。用户看到这个容器对我来说很重要,所以我希望它能够随网站滚动。
我有一个例子:http://gruen-weiss-mannheim.de/
在左侧的这个网站上,它是一个绿色容器,如果有人滚动,它会在网站上保持平滑滚动。
我希望你能帮助我,因为我已经尝试了一些东西,但这样容器总是在顶部。
会很棒如果你能帮我找到解决方案!
try {
window.onscroll = setNavPosition;
}
catch(e) {
document.documentElement.onscroll = setNavPosition;
}
function setNavPosition(){
$('.smooth').stop();
try {
if (document.body.scrollTop > document.documentElement.scrollTop) {
var targetPosition = document.body.scrollTop;
}
else {
var targetPosition = document.documentElement.scrollTop;
}
}
catch(e) {
var targetPosition = document.documentElement.scrollTop;
}
$('.smooth').animate({top: targetPosition}, 600);
}
.smooth {
height: 40px;
background-color: orange;
z-index: 2;
position: absolute;
width: 50px;
top: 50px;
}
.body {
height: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body"></div>
<div class="smooth"></div>
所以每次滚动时,容器都会回到顶部,而不是中间的空间......
答案 0 :(得分:1)
如果您的意思是在第一次滚动后它始终在视口的边缘停止,那是因为这一行var targetPosition = document.body.scrollTop;
和var targetPosition = document.documentElement.scrollTop;
。我改变了它们:
try {
window.onscroll = setNavPosition;
}
catch(e) {
document.documentElement.onscroll = setNavPosition;
}
function setNavPosition(){
$('.smooth').stop();
try {
if (document.body.scrollTop > document.documentElement.scrollTop) {
var targetPosition = document.body.scrollTop + 50;
}
else {
var targetPosition = document.documentElement.scrollTop + 50;
}
}
catch(e) {
var targetPosition = document.documentElement.scrollTop;
}
$('.smooth').animate({top: targetPosition}, 600);
}
&#13;
.smooth {
height: 40px;
background-color: orange;
z-index: 2;
position: absolute;
width: 50px;
top: 50px;
}
.body {
height: 700px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body"></div>
<div class="smooth"></div>
&#13;