问题
var initialCircle;
var i;
var randomXPos;
var randomYPos;
var colorArray;
colorArray=[
'aliceblue','lavender','powderblue','lightblue','lightskyblue','skyblue','deepskyblue','lightsteelblue', 'dodgerblue','cornflowerblue','steelblue','cadetblue','mediumslateblue','slateblue','darkslateblue','royalblue','blue','mediumblue','darkblue','navy','midnightblue','blueviolet', 'indigo'];
var randomColor;
function startBouncingHoverCircles(){for(i=0;i<5;i++){randomXPos = Math.floor(Math.random() * 1200) + 200;randomYPos = Math.floor(Math.random() * 1200) + 200;randomColor=colorArray[Math.floor(Math.random() * colorArray.length)];initialCircle = document.createElement('div');document.body.appendChild(initialCircle);initialCircle.className="circles";initialCircle.style='height:100px;width:100px;border-radius:50%;box-sizing:border-box;position:absolute;border:3px solid green;background-color:'+randomColor;initialCircle.style.top=randomYPos+'px';initialCircle.style.left=randomXPos+'px';setTimeout(function(){document.getElementsByClassName("circles").style.transition="transform 1s";document.getElementsByClassName("circles").style.transform="translate(5px, 5px)"},500)}}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.6.1/randomColor.min.js" integrity="sha512-vPeZ7JCboHcfpqSx5ZD+/jpEhS4JpXxfz9orSvAPPj0EKUVShU2tgy7XkU+oujBJKnWmu4hU7r9MMQNWPfXsYw==" crossorigin="anonymous"></script>
</head>
<body>
<button onClick="startBouncingHoverCircles()">Start</button>
<script src="../Js/bouncingHoverCircles.js"></script>
</body>
</html>
I create twenty five circles by using a for loop and looping through twenty five times. I set within the loop a class name, and I can physically see that the class name is attached to each circle. I'm wondering why when I try to manipulate each element by their class name, the program responds with undefined when trying to get Element by Class Name.
回答1:
I've tested your original code and I confirmed that right result is displayed. I recommend that you will confirm again.
来源:https://stackoverflow.com/questions/65937778/after-creating-div-elements-how-is-it-that-they-may-be-undefined-when-trying-to