在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不是数组。

SELECT DATEPART(year,tbl1.KillDate) AS KillYear,COUNT(Distinct tbl1.AnimalNo) AS N_Killed,COUNT(CASE WHEN tbl2.ConditionId =1 THEN 1 END) AS Type1,COUNT(CASE WHEN tbl2.ConditionId =2 THEN 1 END) AS Type2 FROM tbl1 LEFT JOIN tbl2 ON tbl1.AnimalNo = tbl2.AnimalNo WHERE YEAR(tbl1.KillDate) >=2012 GROUP BY DATEPART(year,KillDate) ORDER BY DATEPART(year,KillDate) 必须为var arrayIDs = "molerat";

此外,您只有1张图片,因此需要将图片数量设置为1

var arrayIDs = ["molerat"];
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;
}

,

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

$(onloadFunction)

否则,您可能需要检查this question中的纯JavaScript $(document).ready(...)替代方案。