使用javascript强制将div从顶部偏移100px?

时间:2014-05-29 11:54:10

标签: javascript

使用scrollto.js脚本使用next / prev按钮从一个部分导航到部分工作正常。 问题是导航滚动到浏览器的顶部。如何让“容器”从浏览器顶部偏移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>

1 个答案:

答案 0 :(得分:1)

这是一个有效的版本: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;
}
  • 我删除了显示:固定;来自.fixed-top-container所以#container总是低于它。
  • 我添加了溢出:auto; #container允许滚动。
  • 我改变了#container的高度。这将在容器中显示滚动条,但我确定有隐藏它的方法。你可能不喜欢这样,但这是我能让它完全像你想要的那样工作的唯一方式。

我认为是这样的。参见JSFiddle。

我已经看到某个人能够通过始终使元素的宽度比窗口稍大一些来隐藏滚动条,因此滚动条总是在屏幕外。这可能是你可以尝试的。

我希望这会有所帮助。 :)