将一个div元素定位到另一个元素的x和y偏移位置

3

你好!我正在尝试使用JavaScript创建一个函数,该函数将创建一个具有与触发按钮/ div稍微偏离的div元素。好消息是,只要触发了其中之一的效果,就会创建至少这么多元素。坏消息是,divXY样式不正常。

代码实际上非常简短,我已经发布了一些注释以使其更易读,运行函数时没有任何错误,所以我真的不知道错误在哪里。

<!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
谢谢您的输入,但这不是问题所在。'<script>'标签不一定要放在'<head>'元素中。 - Stanimirovv
但它们不在<html>标签内 - 你能做到吗? - imulsion
1个回答

1

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

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

示例代码:http://jsfiddle.net/MLmCM/


没错!这次我会记得加像素。谢谢。 - Stanimirovv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接