[英]Forcefully offset div by 100px from the top using javascript?
使用scrollto.js脚本使用“下一个/上一个”按钮在各部分之间导航时效果很好。 问题是导航滚动到浏览器顶部。 如何使“容器”从浏览器顶部偏移100px。 (由于固定的“顶部容器”)
(未尝试在CSS中尝试所有方法,并认为答案在javascript中)
有没有一种方法可以在不修改scrollto脚本的情况下强制div从顶部偏移?
<!-- FIXED TOP CONTAINER 100px -->
<div id="fixed-top-container">
...
</div>
<!-- PREVIOUS / NEXT -->
<a id="prev" href="#">
<div id="float-previous">
</div>
</a> <a id="next" href="#">
<div id="float-next">
</div>
</a>
<!-- CONTAINER -->
<div id="container">
<!-- SECTION 1 -->
<div class="section current" id="section-1">Height:200px</div>
<!-- SECTION 2 -->
<div class="section" id="section-2">Height:400px</div>
<!-- SECTION 3 -->
<div class="section" id="section-3">Height:800px</div>
<!-- SECTION 4 -->
<div class="section" id="section-4">Height:900px</div>
<!-- SECTION 5 -->
<div class="section" id="section-5"><span class="style1">Height</span>:1000px</div>
</div>
<!-- SCRIPT -->
<script>
$(function() {
function scroll(direction) {
var scroll, i,
positions = [],
here = $(window).scrollTop(),
collection = $('.section');
collection.each(function() {
positions.push(parseInt($(this).offset()['top'],10));
});
for(i = 0; i < positions.length; i++) {
if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i-1); break; }
}
if (scroll) {
$.scrollTo(scroll, {
duration: 600
});
}
return false;
}
$("#next,#prev").click(function() {
return scroll($(this).attr('id'));
});
$(".scrolltoanchor").click(function() {
$.scrollTo($($(this).attr("href")), {
duration: 600
});
return false;
});
});
</script>
这是一个工作版本: http : //jsfiddle.net/xU5BB/5/
我改变了什么:
您不需要在滚动功能中循环。 您只需要一个变量来跟踪当前部分,因此我在滚动功能中做了很多更改。 这可能不是必需的,但现在效率更高。 :)
新功能:
var current = 0; // be sure to declare as global (or pass as as argument)
function scroll(direction) {
var scroll,
collection = $('.section');
if (direction == 'next') {
if (current < collection.length - 1) {
scroll = collection.get(current + 1);
current++;
}
} else if (direction == 'prev') {
if (current > 0) {
scroll = collection.get(current - 1);
current--;
}
}
if (scroll) {
$("#container").scrollTo(scroll, {
duration: 100
});
}
return false;
}
我想就是这样。 参见JSFiddle。
我见过某处有人能够通过始终使元素的宽度比窗口大一点来隐藏滚动条,从而使滚动条始终不在屏幕上。 您可以尝试一下。
我希望这有帮助。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.