html - 使用按钮随机更改 h1 的位置
问题描述
h1
按下按钮后,我必须随机更改标题的位置。
这是我的代码:
HTML 声明
function move() {
console.log("MOVE");
var text = document.getElementById("text_to_move");
text.style.positon = "absolute";
text.style.left = randomposition();
text.style.top = randomposition();
}
function randomposition() {
var x = Math.floor(Math.random() * 100) // RANDOM NUMBER BETWEEN 0 AND 100
var y = x + "px";
console.log(y);
return y;
}
<header id="header">
<h1 id="text_to_move">
TITLE
</h1>
</header>
<input type="button" value="MOVE" onclick="move()">
¿ 有什么建议吗?
解决方案
您需要设置position:relative
为 id #text_to_move:
这是更新的代码片段:
function move() {
console.log("MOVE");
var text = document.getElementById("text_to_move");
text.style.positon = "absolute";
text.style.left = randomposition();
text.style.top = randomposition();
}
function randomposition() {
var x = Math.floor(Math.random() * 100) // RANDOM NUMBER BETWEEN 0 AND 100
var y = x + "px";
console.log(y);
return y;
}
#text_to_move{
position:relative;
}
<header id="header">
<h1 id="text_to_move">
TITLE
</h1>
</header>
<input type="button" value="MOVE" onclick="move()">
推荐阅读
- php - PHP7.3:如何在不在子类中重新声明的情况下,继承具有最大可能范围的受保护静态属性?
- mysql - 根据项目从两个 sql 表中求和和差异 - laravel
- css - 在 Safari 中垂直拉伸的图像,父容器作为 display flex
- c++ - 我应该将结构用作 C++ 中的参数化构造函数吗?
- android - 如何为电子商务 Android 应用程序制作管理面板或管理应用程序
- php - 有很多列的 SQL 的另一种解决方案吗
- php - 在 NGINX 服务器上运行多个 CakePHP 项目
- excel - 为什么 Excel 2016 VBA 代码在使用几次后会崩溃?
- scala - Spark 中多个 DataFrame 的并行写入
- android - android:textAllCaps=“false” 不适用于 com.google.android.material.tabs.TabLayout