首页 > 解决方案 > 如何使用 javascript 让 html 元素移动到随机位置?

问题描述

我尝试使用此代码:

<!DOCTYPE html>
<html>
    <head>
    <style> 
    #myDIV {
        position: absolute;
        background-color: coral;
        color: white;
    }
    </style>
    </head>
    <body>

    <p>Click the "Try it" button to position the DIV element 100 pixels from 
    the 
    right edge:</p>
    <p><strong>Note:</strong> If the position property is set to "static", the 
    right 
    property has no effect.</p>

    <button onclick="myFunction()">Try it</button>

    <div id="myDIV">
     <h1>myDIV</h1>
    </div>

    <script>
    function myFunction() {
        document.getElementById("myDIV").style.right = Math.floor(Math.random() 
    * 1) 
    + 100.px  ;
    }
    </script>

    </body>
</html>

但它仍然不起作用!虽然我没有尝试太多。

标签: javascripthtmlcss

解决方案


基本解决方案

这会将 放置div到视口中的任意位置 (x/y)。我添加了一个transition让事情变得更顺畅。

在此处输入图像描述

const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const box = document.getElementById("myDIV");

btn.addEventListener("click", () => {
  let randY = Math.floor((Math.random() * height) + 1);
  let randX = Math.floor((Math.random() * width) + 1);
  box.style.top = randY + "px";
  box.style.right = randX + "px";
});
#myDIV {
  --div-width: 100px;
  position: absolute;
  background-color: coral;
  color: white;
  transition: .5s top, .5s right;
  top: 0;  
  right: calc(100% - var(--div-width));
  width: var(--div-width);
}

button {
  z-index: 1;
  position: absolute;
}
<button>Try it</button>

<div id="myDIV">
  <h1>myDIV</h1>
</div>

jsFiddle

更好的解决方案

动画topleft/right性能不是很好,应该用transforms 代替。使用 atransform移动东西会激活硬件加速。系统将使用其 GPU 来执行与原生应用程序性能一样流畅的动画。如果您正在制作如您所提到的游戏,您将希望在移动环境中使其类似于应用程序。

const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const box = document.getElementById("myDIV");

btn.addEventListener("click", () => {
  let randY = Math.floor((Math.random() * height) + 1);
  let randX = Math.floor((Math.random() * width) + 1);
  box.style.transform = `translate(${randX}px, ${randY}px)`;
});
#myDIV {
  --div-width: 100px;
  position: absolute;
  background-color: coral;
  color: white;
  transition: 0.5s transform;
  top: 0;  
  width: var(--div-width);
}

button {
  z-index: 1;
  position: absolute;
}
<button>Try it</button>

<div id="myDIV">
  <h1>myDIV</h1>
</div>

jsFiddle


推荐阅读