使用JS动态生成图像

时间:2017-05-27 17:54:14

标签: javascript html css

作为Coursera练习的一部分,我试图在<div>的5个不同位置显示相同的照片。虽然我使用absolute定位,但所有照片似乎都堆叠在一起。

这是我试图在body标签中使用的代码:

      <div id="leftside"></div>
      <script type="text/javascript">
      var theLeftSide = document.getElementById("leftside");
      function generateFaces(){
        for (var i = 0; i < 5; i++) {
          photo = document.createElement("img");
          photo.src ="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
              topPosition = Math.floor(Math.random()*401);
              leftPosition = Math.floor(Math.random()*401);
              photo.style.top =topPosition;
              photo.style.left =leftPosition;
              theLeftSide.appendChild(photo);
              console.log(i, topPosition, leftPosition);
            } // for
          } // function
          window.onload = generateFaces();
</script>

2 个答案:

答案 0 :(得分:2)

你在单位中遗漏了单位。如果您只提供号码,则会被忽略

尝试更改为:

<html>

<head>
  <title>Testing Split Div</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB3TtNWWpFpdGV7z0gWnd7-ml0weTLrtGI&callback=initMap" async defer></script>


  <body>
    <div class="container-fluid">
      <div class="row">
        <div class="col" id="q">Lorem ipsum dolor sit amet, modo interesset at vim, et vix oporteat vituperatoribus. Numquam nominavi deseruisse pri ut. At vix animal lobortis, oblique fierent expetendis has ea. Quas graeci aeterno at mei. Et duo voluptatum scripserit, quo habeo
          tamquam at. Ornatus maiorum elaboraret te mea. Civibus omnesque accusamus mel at. Oratio labitur pro ei, vel an legere altera commune, veniam neglegentur no qui. Vel cu soluta adversarium. Ex idque aeterno est, cu nec aperiam constituam mediocritatem.
          Vix propriae incorrupte an, malis congue concludaturque no his. Meliore deseruisse cum te. Usu ex homero assueverit. Summo iudico dolores cu eum, eum falli deterruisset ut. Eu evertitur forensibus philosophia est, alterum phaedrum principes
          te est. No pri recteque percipitur. Eu sumo zril rationibus vel. Possit impetus ex has. Impetus delenit ea mel, sit aliquip recusabo ex, cum nibh sensibus ex. Sed an ubique aliquip alienum, exerci detraxit ea eam. </div>

        <div class="col" id="e"> </div>
      </div>
    </div>
  </body>

</html>

&#13;
&#13;
var  topPosition = Math.floor(Math.random()*401) +'px';
var  leftPosition = Math.floor(Math.random()*401) +'px';
                                                 // ^^ units needed
&#13;
var theLeftSide = document.getElementById("leftside");

function generateFaces() {
  for (var i = 0; i < 5; i++) {
    var photo = document.createElement("img");
    photo.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
    var topPosition = Math.floor(Math.random() * 401) + 'px';
    var leftPosition = Math.floor(Math.random() * 401) + 'px';
    //console.log()
    photo.style.top = topPosition;
    photo.style.left = leftPosition;
    theLeftSide.appendChild(photo);
    console.log(i, topPosition, leftPosition);
  } // for
} // function
window.onload = generateFaces;
&#13;
img {
  position: absolute
}
&#13;
&#13;
&#13;

另请注意,<div id="leftside"></div>不正确。您希望将函数作为引用传递,而不是调用它.... window.onload = generateFaces();

答案 1 :(得分:0)

父元素(或某些祖先)必须至少>>> print 100//18 5 >>> print ((10**2)//9*2) 22 才能让其子级position: relative生效。

在这个答案中有完整的解释:Absolute positioning and its parent element

将此样式添加到您的对象:

position