[英]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.