gpt4 book ai didi

javascript - 使用另一个元素的 x 和 y 偏移定位一个 div 元素

转载 作者:行者123 更新时间:2023-11-28 03:31:41 25 4
gpt4 key购买 nike

美好的一天!我正在尝试使用 javascript 创建一个函数,该函数将创建一个 div 元素,该元素与触发按钮/div 的偏移量很小。好消息是至少创建了与触发其中一个效果一样多的元素。坏消息是 div 的 XY 的样式无法正常工作。

代码实际上很短,我已经发布了一些注释以使其更具可读性,运行该函数时我没有出现任何错误,所以我真的不知道错误在哪里。

<!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>

最佳答案

以这种方式设置时,您需要为您的样式值添加“px”。见:

    box.style.left = x+"px";
box.style.top = (y -10)+"px";

fiddle :http://jsfiddle.net/MLmCM/

关于javascript - 使用另一个元素的 x 和 y 偏移定位一个 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17388493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com