Home > Software design >  the function is not linked to a photo
the function is not linked to a photo

Time:11-01

In theory, when the cursor approaches the photo, the picture should run away from the mouse to a random place, but I've been sitting for an hour and I can't understand why it doesn't work. Help plz((

let Left, Top, MaxLeft, MaxTop;
let image = document.createElement("img");
image.src = "https://yt3.ggpht.com/ytc/AKedOLT0j7uXO5xZs2Ovqr97bnSTb8leTEZqu9zlPyLFGg=s900-c-k-c0x00ffffff-no-rj";
image.width = "300";
image.height = "300";

let div1 = document.createElement('div');
div1.id = 'im'
div1.append(image);
document.body.append(div1);
elem = document.getElementById('im');

MaxLeft = document.documentElement.clientWidth - elem.offsetWidth;
MaxTop = document.documentElement.clientHeight - elem.offsetHeight;
elem.onmousemove = handler;

function handler() {
  Left = Math.random() * MaxLeft;
  elem.style.left = Left   'px';
  Top = Math.random() * MaxTop;
  elem.style.top = Top   'px';
  console.log(Left   ' - '   Top);
}
<!doctype html>
<html lang="ru">

<head>
  <meta charset="UTF-8">
  <title>Кошки-мышки, наверное</title>
</head>

<body>
</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The problem is that the default CSS position property of the div is static and when the position is set to that, changing the top and left properties has no effect (more details).

To fix that, you can change the div's position to relative, something like this:

div1.style.position = 'relative';

Here is a working example, I've made the image smaller so it will fit.

let Left, Top, MaxLeft, MaxTop;
let image = document.createElement("img");
image.src = "https://yt3.ggpht.com/ytc/AKedOLT0j7uXO5xZs2Ovqr97bnSTb8leTEZqu9zlPyLFGg=s900-c-k-c0x00ffffff-no-rj";
image.width = "50";
image.height = "50";

let div1 = document.createElement('div');
div1.id = 'im'
div1.style.position = 'relative';
div1.append(image);
document.body.append(div1);
elem = document.getElementById('im');

MaxLeft = document.documentElement.clientWidth - elem.offsetWidth;
MaxTop = document.documentElement.clientHeight - elem.offsetHeight;
elem.onmousemove = handler;

function handler() {
  Left = Math.random() * MaxLeft;
  elem.style.left = Left   'px';
  Top = Math.random() * MaxTop;
  elem.style.top = Top   'px';
  console.log(Left   ' - '   Top);
}
<!doctype html>
<html lang="ru">

<head>
  <meta charset="UTF-8">
  <title>Кошки-мышки, наверное</title>
</head>

<body>
</body>

</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related