3

再会!使用javascript,我正在尝试创建一个函数,该函数将创建一个div与触发按钮/ div 有小偏移的元素。好消息是,至少创建的元素数量与触发的效果之一一样多。坏消息是divXYdiv 的样式不能正常工作。

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

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

1 回答 1

1

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

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

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

于 2013-06-30T08:37:28.970 回答