最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

css - Basic JavaScript: random positioning - Stack Overflow

programmeradmin1浏览0评论

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'; // 
发布评论

评论列表(0)

  1. 暂无评论