如何在javascript中随机移动图片

时间:2017-05-31 16:43:05

标签: javascript html

当我使用addEventListener单击鼠标时,如何随机移动球 我试过这段代码,但图片并没有动。这段代码出了什么问题?

html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="work.js"></script>

<link type="text/css" rel="stylesheet" href="work.css">
</head>

<body>

<div id = "frame" >
<div id = "net1"> </div>
<div id = "net2"> </div>
<div id = "centerPoint"> </div>
<div id = "centerLine"> </div>
<img src="SoccerBall.png" width="40" alt="Ball" class="moveBall">
</div>

</body>

</html>

javascript代码

var ball = document.querySelector('.moveBall');
function bbb(){

var ball = document.querySelector('.moveBall');

var x = Math.floor(Math.random()*300);
var y = Math.floor(Math.random()*300); 
ball.style.left = x + 'px';
ball.style.top = y + 'px';
};

document.querySelector('#frame').addEventListener('click',bbb);

这是我的css代码:

     #frame{
         border:solid thick red;
         border-width:3px;
         padding-left:9px;
         padding-top:6px; 
         padding-bottom:6px;
         margin:2px;
         width:1220px;
         height:1000px;
         float:right;
         background-color:green;

      }


 .moveBall {
    position:absolute;
    top: 0px; 
    left: 0px; 
     }
  #net1{

 background-color: lightgray;
 width: 400px;
 padding: 40px;
 margin: auto;

  }

 #net2{

 background-color: lightgray;
 width: 400px;
 padding:40px;
 margin:auto;
 margin-top:840px;

1 个答案:

答案 0 :(得分:2)

将样式position:absolute添加到球

(function() {
  function bbb(){

   var ball = document.querySelector('.moveBall');
console.log(ball);
   var x = Math.floor(Math.random()*300);
    var y = Math.floor(Math.random()*300); 
   ball.style.left = x + 'px';
   ball.style.top = y + 'px';
 };
 
document.querySelector('#frame').addEventListener('click',bbb);

})();
#frame{
   border:solid thick red;
   border-width:3px;
   padding-left:9px;
   padding-top:6px; 
   padding-bottom:6px;
   margin:2px;
   width:1220px;
   height:1000px;
   float:right;
   background-color:green;

}


.moveBall {
width:40px;
height:40px;
  position:absolute;
  top: 0px; 
  left: 0px;
  border-radius:50%;
  
  border:1px solid red;
 }
 
  #net1{ 
   background-color: lightgray;
   width: 400px;
   padding: 40px;
    margin: auto; 
  }

 #net2{ 
   background-color: lightgray;
   width: 400px;
   padding:40px;
   margin:auto;
   margin-top:840px;
 }
<div id = "frame" >
  <div id = "net1"> </div>
  <div id = "net2"> </div>
  <div id = "centerPoint"> </div>
   <div id = "centerLine"> </div>
  <img src="http://via.placeholder.com/350x150" width="40" alt="Ball" class="moveBall">
</div>