javascript - 如何使用 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>
但它仍然不起作用!虽然我没有尝试太多。
解决方案
基本解决方案
这会将 放置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>
更好的解决方案
动画top
和left
/right
性能不是很好,应该用transform
s 代替。使用 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>
推荐阅读
- ios - Swift textview 成长方向
- excel - Excel vba用于列A上的范围复制不同列的值
- java-8 - 使用 Java 8 在字段中保存值
- azure - 在一个 azure 存储帐户中获取容器列表并在另一个存储帐户中创建相同的
- playframework-2.6 - Play 2.6 - Java - 事务管理
- c++ - C++ 中的简单字符验证
- c# - Twilio 下载记录到 JsonConvert.DeserializeObject() 上的文件抛出错误
- javascript - 下拉选择菜单以返回没有提交按钮的 php 变量
- java - 在 Maven 命令中传递 env 变量
- google-app-engine - App Engine 项目中应在何处连接 django 信号处理程序