【问题标题】:Why my image is not following the cursor?为什么我的图像没有跟随光标?
【发布时间】:2021-04-23 07:30:03
【问题描述】:

我希望我的图像跟随光标,但我使用的代码不起作用。我无法解决这里的问题。

代码预览:

function followIt(e){

    var img=document.getElementById("img");

    img.style.left = e.clientX;
    img.style.top = e.clientY;

}
<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
</head>

<style>
    #img{
        box-shadow: 0px 0px 1px 1px #000000;
        width: 100px;
    }
</style>

<body id="demo_body" onmousemove="followIt(event)">
<img src="https://i.postimg.cc/g02SqdrF/followmouse.png" id="img">
</body>

<script src="script.js" text="text/javascript"></script>
</html>

【问题讨论】:

  • 提示:不要使用内联 JS on* 属性 - 就像你希望不要使用内联 style 属性一样。 Script 和 Style 应该只在一个地方,那就是它们各自的标签或文件。

标签: javascript html css dom-events


【解决方案1】:
  • 为您的图像使用 CSS position: fixed;,因为 clientX/Y 是相对于 视口
  • 在JS中使用缺少的"px"
  • 使用addEventListener() 代替内联on* 处理程序
  • 不要在昂贵的循环中查询 DOM,将元素缓存在变量中一次,然后在函数中使用其变量引用

const EL_img = document.querySelector("#img");

function followIt(e) {
  EL_img.style.left = e.clientX + "px";
  EL_img.style.top  = e.clientY + "px";
  // Or also:
  // EL_img.style.cssText = `left: ${e.clientX}px; top: ${e.clientY}px;`;
}

window.addEventListener("mousemove", followIt);
#img{
  position: fixed;
  box-shadow: 0px 0px 1px 1px #000000;
  width: 100px;
}
&lt;img id="img" src="https://i.postimg.cc/g02SqdrF/followmouse.png" &gt;

【讨论】:

  • @mplungjan 如果你还记得的话,clientX 和 clientY 总是从视口看的相对单位——这对于position: fixed 来说是最好的。你可以这样做 - 因为它也与视口有关。
  • @verna 修正了一个较小的错字。不客气。
猜你喜欢
  • 1970-01-01
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 2016-03-10
  • 2021-01-15
相关资源
最近更新 更多