我必须在按下按钮后随机更改标题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()">
有什么建议吗?
答案 0 :(得分:1)
您需要将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()">
答案 1 :(得分:0)
k = 1785
function move() {
console.log("MOVE");
var text = document.getElementById("text_to_move");
text.style.left = randomposition();
text.style.top = randomposition();
text.style.position = "absolute";
}
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()">