简体   繁体   中英

Is there an elegant way to randomize div position within jscroll?

I lay out a series of divs in random, non-overlapping positions.

I use jscroll to add more divs when the user reaches the bottom of the page. However, those new divs should also be randomly placed and absolutely positioned.

What is an efficient way to do this? I'm having trouble both (1) applying the random position javascript to new elements and (2) providing a reasonable non-laggy experience.

Current base code: if I were randomly adding dots with endless scroll, how would I get the new set of dots to be randomly placed?

<head>
    <title>desert</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.jscroll/2.2.4/jquery.jscroll.min.js"></script>
</head>

<body>
    <div class="word">
        .
    </div>
    <div class="word">
        .
    </div>
    <div class="word">
        .
    </div>

    <a href="extrastuff.html"></a>

    </div>

    <script>
        ** Randomly assigns .word elements a non - overlapping position **
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#desert').jscroll({
                padding: 2000,
                loadingHtml: ''
            });
        });
    </script>
</body>

</html>

For the non laggy experience you should put the random divs into groups. Each group would be a div that takes the total screen height, so it's just like scrolling on invisible page, and you would only have to create the groups one by one, each time the previous one has reached a certain amount of scroll.

For the position, the groups must be in "position:relative" so the dots inside can be in "position:absolute" and will automaticaly refer to the parent group.

You could generate each page with just a jquery string, by first calculating the screen height, and create the div with relative position, and then apply random position inside a loop :

var screenHeight = (calculate screen height here);

var group = '<div class="page" style="height:'+screenHeight+'px;width:100%; position:relative;">';
for(var i=0;i<4;i++)
{

    group += '<div class="word" style="top:'+Math.random()*100+'%;left:'+Math.random()*100+';position:absolute;" >.</div>';
}
group += '</div>';

body.append(group);

This is the basic code to apply on each certain amount of scroll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM