首页 > 解决方案 > 使用按钮随机更改 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()">

¿ 有什么建议吗?

标签: htmlbuttonposition

解决方案


您需要设置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()">


推荐阅读