为什么body元素需要高度才能使视差滚动工作?

时间:2017-01-15 19:20:29

标签: javascript css typescript parallax

我一直在尝试用js和css创建视差滚动。一切正常但我有一行代码我需要但我不知道为什么。工作代码如下。

CSS

/// Block Element
/// @access public
/// @param {String} $element - Element's name
@mixin element($element) {
    &__#{$element} {
        @content;
    }
}

/// Block Modifier
/// @access public
/// @param {String} $modifier - Modifier's name
@mixin modifier($modifier) {
    &--#{$modifier} {
        @content;
    }
}


.body {
    height: 2000px;
}
.layer {
    width: 100%;
    height: 800px;
    position: fixed;
    //z-index: -1;
    background-color: pink;

    @include element('1') {
        background-color: blue;
    }

    @include element('2') {
        background-color: red;
    }

    @include element('3') {
        background-color: green;
    }
}

的Javascript

import "./index.scss";
import "./bootstrap/css/bootstrap.min.css";
window.onload = function () {
    let layers = window.document.querySelectorAll(".layer")
    console.log("Layers: " + layers);
    window.addEventListener("scroll", (event) => {
        let topDistance = window.pageYOffset;
        for (let i = 0; i < layers.length; i++) {
            let layer = <HTMLElement>layers[i];
            let depth = layer.dataset["depth"];
            let movement = -(topDistance * Number(depth))
            let translate3d = 'translate3d(0, ' + movement + 'px, 0)';
            layer.style['-webkit-transform'] = translate3d;
            layer.style['-moz-transform'] = translate3d;
            layer.style['-ms-transform'] = translate3d;
            layer.style['-o-transform'] = translate3d;
            layer.style.transform = translate3d;
        }
    });
}

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Introduction to web development blog </title>
    <link href="https://fonts.googleapis.com/css?family=Bungee+Shade|Oswald|Raleway" rel="stylesheet">
    <script src="bundle/index.js"></script>
</head>
<body class="body">
    <div class="hero">
        <h1>Boom</h1>
        <div class="layer layer__1" data-type="parallax" data-depth="0.5"></div>
        <div class="layer layer__2" data-type="parallax" data-depth="0.1">
            <h1>Layer 2</h1>
        </div>
        <div class="layer layer__3" data-type="parallax" data-depth="0.2"></div>

    </div>
</body>
</html>

此代码有效,但如果我删除

.body {
    height: 2000px;
}

它不再有效。为什么是这样?

提前致谢。

0 个答案:

没有答案