当鼠标指针进入元素时,更改div随机数的位置

时间:2019-01-11 11:23:45

标签: javascript jquery html css

我不知道如何在jquery的循环中创建div,以及如何使用“ mouseover”功能更改它们的位置。这是我创建div元素的代码,但是元素的位置没有改变。谁能帮助我更正我的代码?

var r, g, b, counter, i;
//generate random number between 20 and number.
function generateRandomNumber(number) {
  return Math.floor(Math.random() * (number - 20)) + 20;
}
// maximum number of random elements is 30.
counter = generateRandomNumber(30);
for (i = 0; i < counter; i++) {
  var div = $("<div/>");
  div.id = "randomlyPlaced" + i;
  //random style for the elements
  r = generateRandomNumber(255);
  g = generateRandomNumber(255);
  b = generateRandomNumber(255);
  $(div).css({
    position: "absolute",
    background: "rgb(" + r + "," + g + "," + b + ")",
    height: generateRandomNumber(200) + "px",
    width: generateRandomNumber(400) + "px",
    top: generateRandomNumber(500) + "px",
    left: generateRandomNumber(1000) + "px"
  });
  //append the elements to body.
  $('body').append(div);
  //change the position of the element.
  $("#" + div.id).mouseover(function() {
    $(this).animate({
      top: generateRandomNumber(500) + "px",
      left: generateRandomNumber(1000)
    }, 500, "linear");
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>Randomly Placed Animated rectangles</title>
</head>

<body style="width: 80%; height: 80%; background-color :rgb(164, 173, 
    226); position:relative;">
  <div id='+div.id+'></div>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您需要使用div对象本身而不是"#"+div.id,原因是当在DOM中加载元素时此id起作用,而在动态生成div的情况下就不是这样。

$(div).mouseover(function(){
  $(this).animate({
         top: generateRandomNumber(500) + "px", 
         left:generateRandomNumber(1000)
      },500,"linear");
});

检查小提琴https://jsfiddle.net/stdeepak22/t5w6cm9x/