刷新页面时的随机图像位置

问题描述 投票:0回答:1

我有这段代码,当鼠标单击图像时,它会拖动图像,但是我希望图像在每次刷新页面时都显示在随机位置。我怎样才能做到这一点?谢谢! :)

到目前为止,我得到的代码是

<div class="photos">
<div id="connie1">
 <img src="img/connieimage.jpeg"></img>
</div>

<div id="rocio1">
 <img src="img/rocioimage.mp4"></img>
</div>

var connie = document.getElementById("connie1");
var rocio = document.getElementById("rocio1");
var moving = false;

connie.addEventListener("mousedown", initialClick, false);
rocio.addEventListener("mousedown", initialClick, false);


function move(e){

var newX = e.clientX - 10;
var newY = e.clientY - 10;

image.style.left = newX + "px";
image.style.top = newY + "px";


}

function initialClick(e) {

if(moving){
document.removeEventListener("mousemove", move);
moving = !moving;
return;
}

moving = !moving;
image = this;

document.addEventListener("mousemove", move, false);

}
javascript html random mouse drag
1个回答
0
投票

为了使图像在页面加载时处于随机位置,而不是让它们走出屏幕窗口使用此代码

Javascript

function onloadFunction() {
  var amount = X; //The amount of loops
  var arrayIDs = ["imgID1", "imgID2", "imgID3"];    //all the IDs of the images

  for (i=1;i<=amount;i++) {

   //First get the image height and width in a var
   var element = document.getElementById(arrayIDs[i-1]);
   var positionInfo = element.getBoundingClientRect();
   var imgHeight = positionInfo.height;
   var imgWidth = positionInfo.width;

   //Then get the width and height of the screen. if the container is not the screen
   //use the same code as above for the image width/height and change the imgID
   //The the Id of the container element.
   var screenWidth = window.innerWidth;
   var screenHeight = window.innerHeight;

   //Now generate a random top and left position for the image on page load
   var imgLeft = Math.floor(Math.random() * (screenWidth - imgWidth)); 
   var imgTop= Math.floor(Math.random() * (screenHeight - imgHeight)); 

   //The reason to get the img and screen height and width is to not let the 
   //image
   //overlap out of the screen 


   //Now set the image to correct position
   document.getElementById(arrayIDs[i-1]).style.top = imgTop+"px";
   document.getElementById(arrayIDs[i-1]).style.left = imgLeft+"px";
  }
}

HTML

<body onload="onloadFunction()">
   <img class="images"  src="img/connieimage.jpeg" id="imgID1"></img>
   <img class="images" src="img/connieimage.jpeg" id="imgID2"></img>
   <img class="images"  src="img/connieimage.jpeg" id="imgID3"></img>
</body>

CSS

.images {
  position: absolute;
}
© www.soinside.com 2019 - 2024. All rights reserved.