簡體   English   中英

在 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)

否則你可能想檢查這個問題是否有純 JavaScript $(document).ready(...)替代方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM