如何在mousemove上移动多个元素

时间:2018-06-01 09:42:39

标签: javascript html css transform elements

如何使用 Javascript 选择多个元素并同时移动它们?我试图在不使用jQuery的情况下制作这样的东西:https://jenniferdewalt.com/caterpillar.html

// JavaScript source code
var container = document.getElementById("container");
//MAKE NEW DIV
//container.innerHTML = '<div id="circle" class="circle"></div>';
console.log(container.innerHTML);
var mouseX = 0;
var mouseY = 0;
var positionX = 0;
var positionY = 0;
var speed = 50;
var i;
var m = 0;

var newCircle;

//EVENTS / TRIGGERS
window.addEventListener("mousemove", mouseCoords);
setInterval(circlePosition, 30);

//Make Circles
makeCircles(20);

function makeCircles(num) {
  for (i = 0; i < num; i++) {
    container.innerHTML += '<div id="circle' + i + '" class="circle"></div> ';
    //Circle with NEW ID
    var newCircle = document.getElementById("circle" + i);
    //This Circle Random Color;
    var ranColor = genColor();
    newCircle.style.backgroundColor = ranColor;
    //This Circle Random Size;
    var newSize = genSize();

    newCircle.style.width = newSize + "px";
    newCircle.style.height = newSize + "px";
  }
}

console.log(container.innerHTML);

//FUNCTIONS.
//MOUSE COORDS
function mouseCoords(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
}

//CIRCLEPOSITION
function circlePosition() {
  //Circle go's to Last Mouse position
  var circleX = document.getElementById("circle0");
  var circleY = document.getElementById("circle0");

  positionX += (mouseX - positionX) / speed;
  positionY += (mouseY - positionY) / speed;
  circleX.style.left = positionX + "px";
  circleY.style.top = positionY + "px";
}


// MOST IMPORTANT PART RELATED TO QUESTION

//Random Color
function genColor() {
  var RGBarr = [];
  for (c = 0; c < 3; c++) {
    var newNum = Math.floor(Math.random() * 256);
    RGBarr.push(newNum);
  }
  var newRGB = 'rgb(' + RGBarr[0] + ',' + RGBarr[1] + ',' + RGBarr[2] + ')';

  return newRGB;
}

//Random Size
function genSize() {
  var ranSize = Math.floor(Math.random() * 100) + 1;
  return ranSize;
}
body {
  background-color: black;
}

.circle {
  position: absolute;
  top: 0;
  left: 0;
  background-color: white;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
  <link href="./HOWTOMOVEAFUCKINGCIRCLE.css" type="text/css" rel="stylesheet" />
  <meta charset="utf-8" />
  <title></title>
</head>

<body>

  <div id="container"></div>
  <!--Javscript-->
  <script src="./HOWTOMOVEAFUCKINGCIRCLE.js"></script>
</body>

</html>

我是自学,所以真的会帮助你,如果你不能被要求帮助我这个项目,请考虑给我一些其他的例子,我可以同时移动多个元素。来自荷兰的问候。

0 个答案:

没有答案