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

时间:2013-06-30 08:17:39

标签: javascript html5 css3

美好的一天!使用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>

1 个答案:

答案 0 :(得分:0)

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

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

小提琴:http://jsfiddle.net/MLmCM/