Javascript 使用另一个元素的x和y偏移定位一个div元素
你好!使用javascript,我试图创建一个函数,该函数将创建一个Javascript 使用另一个元素的x和y偏移定位一个div元素,javascript,html,css,Javascript,Html,Css,你好!使用javascript,我试图创建一个函数,该函数将创建一个div元素,该元素与触发按钮/div之间有一个小偏移量。好消息是,至少创建了与触发一个效果一样多的元素。坏消息是div的X和Y的样式不能正常工作 代码实际上很短,我已经发布了一些注释以提高可读性,我在运行函数时没有收到任何错误,所以我真的不知道错误在哪里 <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <h
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>
/*将创建什么*/
.盒子{
宽度:30px;
高度:30px;
背景色:红色;
}
/*第一个按钮的位置*/
.btm12{
左边距:50%;
利润率最高:5%
}
/*第二个按钮的定位*/
.btm1{
左缘:30%;
利润率最高:10%
}
单击我
点击我
document.getElementById(“btn”).onclick=function(){createBox(this.id);};
document.getElementById(“btn2”).onclick=function(){createBox(this.id);};
函数createBox(IDI){
//获取对元素的引用
var元素=document.getElementById(IDI);
//我们可以访问X和Y坐标的一种方法
var position=element.getBoundingClientRect();
var x=位置。左侧;
var y=position.top;
//创建、设置div元素的X/Y样式并进行设置
变量框=document.createElement(“div”);
box.className=“box”;
box.style.left=x;
box.style.top=y-10;
box.style.position=“绝对”;
//A将元素添加到主体中
文件.正文.附件(框);
}
以这种方式设置样式值时,需要为样式值添加“px”。见:
box.style.left = x+"px";
box.style.top = (y -10)+"px";
Fiddle:我认为它不起作用,因为
标记不在
标记内。将脚本放入
元素谢谢您的输入,但这不是问题所在。“”标记不一定必须是“”元素。但它们不在
标记内-可以这样做吗?这是正确的!这次我会尽量不忘记添加像素。非常感谢。