你好!我正在尝试使用JavaScript创建一个函数,该函数将创建一个具有与触发按钮/ div稍微偏离的div
元素。好消息是,只要触发了其中之一的效果,就会创建至少这么多元素。坏消息是,div
的X
和Y
样式不正常。
代码实际上非常简短,我已经发布了一些注释以使其更易读,运行函数时没有任何错误,所以我真的不知道错误在哪里。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
/*What will be created*/
.box {
width: 30px;
height: 30px;
background-color:red;
}
/*The positioning for the first button*/
.btm12 {
margin-left:50%;
margin-top:5%
}
/*The positioning for the second button*/
.btm1 {
margin-left:30%;
margin-top:10%
}
</style>
</head>
<body>
<button id="btn" onclick="createBox()" class="btm1">Click me</button><br />
<button id="btn2" onclick="createBox()" class="btm12">Click me</button>
</body>
</html>
<script>
document.getElementById("btn").onclick = function () { createBox(this.id); };
document.getElementById("btn2").onclick = function () { createBox(this.id); };
function createBox(IDI) {
//get reference to the element
var element = document.getElementById(IDI);
//a way we can acces the X and Y coordinates
var position = element.getBoundingClientRect();
var x = position.left;
var y = position.top;
//create, style and set the X/Y of the the div element
var box = document.createElement("div");
box.className = "box";
box.style.left = x;
box.style.top = y -10;
box.style.position = "absolute";
//Apend the element to the body
document.body.appendChild(box);
}
</script>
<script>
标签不在<html>
标签内。将脚本放入<head>
元素中。 - imulsion<html>
标签内 - 你能做到吗? - imulsion