JavaScript视差函数 - 如何创建多个实例

时间:2014-08-30 22:16:20

标签: javascript jquery parallax

我正在制作自定义视差背景JavaScript。在这一点上,它工作得很好(正如预期的那样)。不幸的是我是JavaScript新手,所以我的知识有限。当我只需要一个实例时(这就是它的编写方式),我编写的脚本效果很好。 我希望它能够处理多个实例。

现在,它找到了具有类parallax的元素并且它具有魔力。显然,按照它的编写方式,具有“parallax”类的多个实例/元素将不起作用。我完全不知道如何采取下一步并将我的功能单独应用于所有实例。我搜索了很多,但仍然不知道如何继续。 代码附后。最后,我将为$(document).ready$(window).resize$(window).scroll创建一个单独的函数,以节省处理能力,但我不希望这样做,直到我离终点线更近

如何格式化此脚本以使用多个实例(将使用该脚本实现效果的网页的多个部分)?

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0"/>
<title>Test Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
    $(document).ready(function(){
    parallaxReady();
    });

    $(window).resize(function(){
    parallaxReady();
    });

    $(window).scroll(function(){
    parallaxReady();
    });
    function parallaxResize() {}
    function parallaxScroll() {}
    function parallaxReady() {              
        $(".parallax img").width('100%');                                               // This is for window resizing
        $(".parallax img").height('auto');                                              // This is for window resizing
        var winHeight = window.innerHeight;                                             //
        var offset = $(".parallax").offset();                                           //
        var fromTop = offset.top;                                                       //
        var scrollPos = window.pageYOffset;                                             //
        var ratio = -.7;                                                                // I would like to set this individually
        var verticalAlign = 0;                                                          //
        var travel = 0;                                                                 //
        var containerHeight = $(".parallax").css("height");                             // Get container height
        var containerWidth = $(".parallax").css("width");                               // Get container width
            containerHeight = parseInt(containerHeight, 10);                            // Remove px
            containerWidth = parseInt(containerWidth, 10);                              // Remove px
        var imageHeight = $(".parallax img").css("height");                             // Get image height
        var imageWidth = $(".parallax img").css("width");                               // Get image width
            imageHeight = parseInt(imageHeight, 10);                                    // Remove px        
            imageWidth = parseInt(imageWidth, 10);                                      // Remove px

        if (winHeight > containerHeight){                                               // If the container is smaller than Viewport
            travel = (winHeight - containerHeight);                                     // Set travel distance

            if (imageHeight < (containerHeight + (travel * -ratio))){                   // If image is too short
                $(".parallax img").height(containerHeight + (travel * -ratio) + 'px');  // Resize image to height needed
                imageHeight = (containerHeight + (travel * -ratio));                    // Update variable
                $(".parallax img").width('auto');                                       // Set image width to auto
                imageWidth = $(".parallax img").css("width");                           // Update variable
                imageWidth = parseInt(imageWidth, 10);                                  // Remove px
                }
            else {
                verticalAlign = (imageHeight - (containerHeight + (travel * -ratio)))   // Else if image is tall enough, center it vertically
                }                       
            }
        else {                                                                          // Else if container is taller than Viewport
            travel = (containerHeight) - winHeight;                                     // Set travel distance
            $(".parallax img").height(winHeight + (travel * -ratio) + 'px');            // Resize image to height needed
            $(".parallax img").width('auto');                                           // Set image width to auto
            imageWidth = $(".parallax img").css("width");                               // Update variable
            imageWidth = parseInt(imageWidth, 10);                                      // Remove px

            if (imageWidth < containerWidth){                                           // If image width is too short
                $(".parallax img").width(containerWidth);                               // Set image width to 100% container width
                $(".parallax img").height('auto');                                      // Set height to auto
                verticalAlign = (imageHeight - (winHeight + (travel * -ratio)))         // Center it vertically
                }
            }           

        if (imageWidth > containerWidth){                                               // If image width is wider than container
            $(".parallax img").css('left',((imageWidth - containerWidth) * -.5) + 'px');// Center image horizontally
            }
        else {                                                                          // Else if image is not wider than container
            $(".parallax img").css('left','0');                                         // Reset to 0
            }

        var alignment = ((fromTop - winHeight) + containerHeight);                      // The initial height reference for image

        var newPos = (scrollPos * ratio) - ((alignment * ratio) + (verticalAlign *.5)); // Position for Image based on our criteria
        $(".parallax img").css('bottom',newPos + 'px');                                 // Set the new position for image

        $("#debug").text("Scroll Height: " + scrollPos + " | Window Height: " + winHeight + " | DIV Height: " + containerHeight + " | Image Height " + imageHeight + " | Offset: " + fromTop + " | Travel: " + travel + " | Alignment: " + alignment + " | Vertical Align: " + verticalAlign);
        }   
</script>   
<style scoped>
html, body {padding:0;margin:0;font-family:Arial, Helvetica, sans-serif;}
#debug {padding:15px;background:#000;font-size:12px;color:#fff;position:fixed;top:0;left:0;z-index:1000;opacity:.5;}
.spacer {height:70vh;background: #444;}
.longer {height:100vh;}
.parallax {overflow:hidden;position:relative;}
.parallax img {width:100%;position:absolute;bottom:0;}
.parallax div {width:40%;margin:10% auto;padding:5%;position:relative;color:#fff;font-size:36px;text-align:center;background:rgba(0,0,0,0.2);}
.parallax div p {padding:10px 0;margin:0;font-size:15px;text-align:justify;}
</style>
    <div class="spacer"></div>
    <div class="parallax">
        <img alt="parallax" src="http://www.wallpaperup.com/uploads/wallpapers/2012/09/21/15744/3ad1c548edfc58f499feda5b042fb857.jpg">  
        <div>
            This is Random Text
            <p>Lorem ipsum dolor sit amet, mel id errem fierent sensibus, liber similique voluptatibus sit te, cum ea aliquip persequeris. Eam ne hinc labitur suscipit. Te laudem scaevola sea, esse nibh maiorum quo te. Sit enim regione ei, pro te accusamus definitiones. Maiorum perpetua oportere pro eu. Ea mel homero inermis insolens, ut adhuc putent qui.</p>
            <p>Apeirian platonem interpretaris eu quo, wisi audire appetere sea ad. Vis cibo congue libris ut, has ea erat maiorum percipitur. Ius ut doming inciderint, affert eirmod cu sed. Ne mel falli partiendo, ei agam minim legimus sit. Quem omnis mundi pro in, ei viderer mediocritatem quo.</p>
        </div>
    </div>
    <div class="spacer longer"></div>
    <div id="debug"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我喜欢这种效果! javascript中有一些常见的模式来做这样的模块。一种方法如下。

让您的div.parallax成为所有必需品的外部容器,例如:

<div class='parallax'>
    content
</div>

制作parallax“类”。在javascript中,“class”只是遵循某些模式的对象。这将是暴露于全局范围的唯一对象。你的parallaxReady()函数已经危险地接近这个(这很好)。

制作parallax.init()或类似内容。该函数将接受options哈希。您可以为页面上的每个视差div调用此函数,如下所示:

$('div.parallax').forEach(function(element) {
    parallax.init({
        element: element,
        image: "/path/to/my/image.jpg",
    });
});

将您的代码重写为parallax.init()。您当前引用$(".parallax")$(".parallax img")的任何位置或更改的任何内容,以引用传入的动态元素。例如,这一行:

$(".parallax img").width('100%');

会改为

options.element.width('100%');

parallax.init()会在视差容器div中创建所需的任何其他元素 - 比如图像div,间隔符等等。它还将设置所需的任何变量和内容,然后注册滚动事件。看起来你目前在parallaxReady中拥有的大部分代码都会在parallax.init()中的这个滚动事件中结束。

parallax.init()也可以返回某种标识符,以便您可以使用它来调用parallax.stop()。或者你可以把这整个东西变成一个真正的jQuery插件。

我希望这有助于您入门。