在 html/javascript 中刷新页面时如何更改图像的位置?

How can i change the position of an image when page is refreshed in html/javascript?

每次刷新页面时,我都需要将这张图片放在屏幕上的随机位置,我找到了一个可以工作的 javascript 代码,但我不知道如何让它工作.

这是我的html

  <body>
    <p>
      find rufus
    </p>
    <img src="molerat.jpg" id="molerat"></img>
  </body>

javascript:

console.log();
function onloadFunction() {
  var amount = 10;
  var arrayIDs = "molerat"; 

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

   var element = document.getElementById(arrayIDs[i-1]);
   var positionInfo = element.getBoundingClientRect();
   var imgHeight = positionInfo.height;
   var imgWidth = positionInfo.width;


   var screenWidth = window.innerWidth;
   var screenHeight = window.innerHeight;

   var imgLeft = Math.floor(Math.random() * (screenWidth - imgWidth));
   var imgTop= Math.floor(Math.random() * (screenHeight - imgHeight));

   document.getElementById(arrayIDs[i-1]).style.top = imgTop+"px";
   document.getElementById(arrayIDs[i-1]).style.left = imgLeft+"px";
  }
}

css:

body{
  background-color:white;
  font-family: monospace;
  font-size: 50px;
}

img {
  position: absolute;
}

arrayIDs 不是数组。

var arrayIDs = "molerat"; 需要 var arrayIDs = ["molerat"];

另外你只有1张图片所以数量需要设置为1

function onloadFunction() {
  var amount = 1;
  var arrayIDs = ["molerat"]; 

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

   var element = document.getElementById(arrayIDs[i-1]);
   var positionInfo = element.getBoundingClientRect();
   var imgHeight = positionInfo.height;
   var imgWidth = positionInfo.width;


   var screenWidth = window.innerWidth;
   var screenHeight = window.innerHeight;

   var imgLeft = Math.floor(Math.random() * (screenWidth - imgWidth));
   var imgTop= Math.floor(Math.random() * (screenHeight - imgHeight));

   document.getElementById(arrayIDs[i-1]).style.top = imgTop+"px";
   document.getElementById(arrayIDs[i-1]).style.left = imgLeft+"px";
  }
}

onloadFunction();
body{
  background-color: white;
  font-family: monospace;
  font-size: 50px;
}

img {
  position: absolute;
}
<p>
  find rufus
</p>
<img src="https://picsum.photos/200" id="molerat" />

您的 onloadFunction 需要在页面加载时调用。如果您在项目中使用 jQuery,那么 $(document).ready(...) 是正确的选择:

$(onloadFunction)

否则,您可能需要检查 this question 以获得纯 JavaScript $(document).ready(...) 替代品。