图像元素未正确放置在div中

时间:2016-01-21 10:52:35

标签: javascript css dom

我尝试将一个img放在一个div中,在一个特定的地方(200,100),但它总是位于左上角(0,0)。我做错了什么?

{
   "destination_addresses" : [ "Bombay, Maharashtra, Inde" ],
   "origin_addresses" : [ "New Delhi, New Delhi 110001, Inde" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1 457 km",
                  "value" : 1457222
               },
               "duration" : {
                  "text" : "22 heures 8 minutes",
                  "value" : 79663
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

2 个答案:

答案 0 :(得分:5)

您还需要为img设置position。这是jsFiddle



        function build_set() {
            var leftSide = document.getElementById("leftSide");
            var rightSide = document.getElementById("rightSide");
            var smile = document.createElement("img");
            smile.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png")
            smile.style.top = "200px";
            smile.style.left = "100px";
            smile.style.position = "absolute";
            leftSide.appendChild(smile);
        }
        build_set();

    <h1>Matching Game</h1>
    <div id="leftSide" style="position:absolute; top:100px; left:0; width:500px; height:500px"></div>
    <div id="rightside" style="position:absolute; top:100px; left:500px; width:500px; height:500px; border-left:3px solid black"></div> 
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您的图片未定位,因此lefttop将被忽略。

将以下内容添加到您的javascript:

smile.style.position = 'absolute';

这是工作版本的jsFiddle