css - Basic JavaScript: random positioning - Stack Overflow

I'm trying to create a square that will appear in a random place within a 300x300px space.It is

I'm trying to create a square that will appear in a random place within a 300x300px space. It is currently moving horizontally but not vertically. Can someone help me get it to move vertically as well? Thank you!

        #square {width: 200px;
        height: 200px;
        display: none;
        position: relative;
        }

        var top=Math.random();
                top=top*300;                
        var left=Math.random();
                left=left*300;                      
        document.getElementById("square").style.top=top+"px";                   
        document.getElementById("square").style.left=left+"px";       

I'm trying to create a square that will appear in a random place within a 300x300px space. It is currently moving horizontally but not vertically. Can someone help me get it to move vertically as well? Thank you!

        #square {width: 200px;
        height: 200px;
        display: none;
        position: relative;
        }

        var top=Math.random();
                top=top*300;                
        var left=Math.random();
                left=left*300;                      
        document.getElementById("square").style.top=top+"px";                   
        document.getElementById("square").style.left=left+"px";       
Share Improve this question asked Mar 12, 2017 at 21:13 Denise WalterDenise Walter 1231 gold badge4 silver badges6 bronze badges 1
  • 1 Works for me: jsfiddle/f3chy9mk The problem is somewhere else. You'll have to show an example that replicates the problem. – JJJ Commented Mar 12, 2017 at 21:20
Add a ment  | 

2 Answers 2

Reset to default 2

Use left to translate horizontally and top for vertically.

const getRandom = (min, max) => Math.floor(Math.random()*(max-min+1)+min);

const square= document.querySelector('#square');
setInterval(() => {
   square.style.left= getRandom(0, 300 - 200)+'px'; // 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745137538a4613274.html

相关推荐

  • css - Basic JavaScript: random positioning - Stack Overflow

    I'm trying to create a square that will appear in a random place within a 300x300px space.It is

    1小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信