ScrollMagic - 带有锚点链接的TimelineMax页面视差滚动

时间:2016-10-07 06:47:03

标签: greensock scrollmagic

我正在使用ScrollMagic插件进行视差滚动效果。以下是我的代码

HTML代码

    <div style="position:fixed;right:50px;top:50px;width:200px;height:300px;background:#fff;z-index:1">
<div><a href="#one">ONE</a></div>
<div><a href="#two">TWO</a></div>
<div><a href="#three">THREE</a></div>
<div><a href="#four">FOUR</a></div>
</div>
<div id="pinContainer">
<div id="slideContainer">
<section class="panel blue">
<a id="one"></a>
<b>ONE</b>
</section>
<section class="panel turqoise">
<a id="two"></a>
<b>TWO</b>
</section>
<section class="panel green">
<a id="three"></a>
<b>THREE</b>
</section>
<section class="panel bordeaux">
<a id="four"></a>
<b>FOUR</b>
</section>
</div>
</div>

JAVASCRipt代码

    $(function () { // wait for document ready
    // init
    var controller = new ScrollMagic.Controller();

    // define movement of panels
    var wipeAnimation = new TimelineMax()
        // animate to second panel
        .to("#slideContainer", 0.5, {z: -150})      // move back in 3D space
        .to("#slideContainer", 1,   {x: "-25%"})    // move in to first panel
        .to("#slideContainer", 0.5, {z: 0})             // move back to origin in 3D space
        // animate to third panel
        .to("#slideContainer", 0.5, {z: -150, delay: 1})
        .to("#slideContainer", 1,   {x: "-50%"})
        .to("#slideContainer", 0.5, {z: 0})
        // animate to forth panel
        .to("#slideContainer", 0.5, {z: -150, delay: 1})
        .to("#slideContainer", 1,   {x: "-75%"})
        .to("#slideContainer", 0.5, {z: 0});

    // create scene to pin and link animation
    new ScrollMagic.Scene({
            triggerElement: "#pinContainer",
            triggerHook: "onLeave",
            duration: "500%"
        })
        .setPin("#pinContainer")
        .setTween(wipeAnimation)
        .addIndicators() // add indicators (requires plugin)
        .addTo(controller);

    // change behaviour of controller to animate scroll instead of jump
controller.scrollTo(function (newpos) {
    TweenMax.to(window, 0.5, {scrollTo: {y: newpos}});
});

//  bind scroll to anchor links
$(document).on("click", "a[href^='#']", function (e) {
    var id = $(this).attr("href");
    if ($(id).length > 0) {
        e.preventDefault();

        // trigger scroll
        controller.scrollTo(id);

            // if supported by the browser we can even update the URL.
        if (window.history && window.history.pushState) {
            history.pushState("", document.title, id);
        }
    }
});
});

如何使用scrollmagic插件实现锚点滚动功能。

当我点击锚链接时使用上面的代码,它不会进入特定部分。

1 个答案:

答案 0 :(得分:0)

我今天遇到了同样的问题。 尝试用“#pinContainer”元素替换“window”元素。

更改您的代码:

controller.scrollTo(function (newpos) {
    TweenMax.to(window, 0.5, {scrollTo: {y: newpos}});
});

为:

controller.scrollTo(function (newpos) {
    TweenMax.to($('#pinContainer'), 0.5, {scrollTo: {y: newpos}});
});

希望有所帮助。