Safari 和 Chrome 为同一脚本提供不同的结果(document.querySelector)

问题描述 投票:0回答:0

为什么在同一脚本中使用 document.querySelector 时,Safari 和 Chrome 会给出不同的结果?

我想要做的是在将鼠标悬停在链接上时在链接旁边显示图像。图像应显示在链接旁边。 在 Safari 中,图像从左角正确显示,但在 Chrome 中,当我向下滚动并指向链接时,图像从意想不到的角度显示。

JavaScript:

let attached = false;

function showImage() {
  const image = document.querySelector('img');
  if (image && !attached) {
    attached = true;
    image.style.display = 'block';
    document.addEventListener('pointermove', function(event) {
      image.style.left = event.x + 'px';
      image.style.top = event.y + 'px';
    });
  }
}

function hideImage() {
  const image = document.querySelector('img');
  if (image && attached) {
    attached = false;
    image.style.display = 'none';
    document.removeEventListener('pointermove', function(event) {
      image.style.left = event.x + 'px';
      image.style.top = event.y + 'px';
    });
  }
}

CSS:

  img{
    position: fixed;
    display: none;
    pointer-events: none;
    width: 640px;
    height: auto;
  }

我尝试将代码更改为:

let attached = false;

const getElmtImage = (elmt) => {
  return elmt.querySelector("img")
}



const followMouse = (elmt, event) => {
  elmt.style.left = event.x + "px";
  elmt.style.top = event.y + "px";
}

function showImage(elmt) {
  const image = getElmtImage(elmt)
  if (!attached) {
    attached = true;
    image.style.display = "block";
    document.addEventListener("pointermove", function(event) {
      followMouse(image, event)
    });
  }
}

function hideImage(elmt) {
  const image = getElmtImage(elmt)
  attached = false;
  image.style.display = "none";
  document.removeEventListener("pointermove", followMouse);
}```
javascript hugo
© www.soinside.com 2019 - 2024. All rights reserved.