samedi 18 avril 2020

divs with images always get on the top of divs with text when I randomize their position (on load and using setInterval). JavaScript

When I randomize position of some divs with text and some others with images (on load and using setInterval), images always get on the top of the divs with text. I’ve been trying to find a solution by myself but I just started learning how to code a few weeks ago, and I don’t even know what am I looking for. So I’d appreciate if someone could help me. This is my code so far:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
        <title></title>
        <style>
            div{
                position: absolute;
            }
            .description{
                width: 650px;
            }
        </style>
        <script type="text/javascript">
            function Init(){
                divs = document.querySelectorAll("div");
                setInterval (mover, 500);
            }

            function mover(){
                divs.forEach(div => {
                    var spaceH =window.innerHeight - div.clientHeight;
                    var spaceW =window.innerWidth - div.clientWidth;
                    div.style.top=Math.round(Math.random()* spaceH) + "px";
                    div.style.left=Math.round(Math.random()* spaceW) + "px";
                });
            }
        </script>
    </head>
    <body onload="Init()">
        <div class="description">
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        </div>
        <div class="description">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        </div>
        <div><img src="MyImage1.jpg" class="imagenes" alt=""></div>
        <div><img src="MyImage2.jpg" class="imagenes" alt=""></div>
    </body>
</html>

I intend to doit with many divs more. This is just a test. And sorry if I’m not explaining myself properly.




Aucun commentaire:

Enregistrer un commentaire