css 如何创建一个远离光标的按钮?

nwo49xxi  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(69)

我写了一个函数,当光标接近按钮时,它应该改变按钮的位置。不幸的是,按钮停留在同一个位置,除了点击之外,不会对光标做出React(它什么也不做)。我看到了类似的问题,但该代码没有做我需要的事情。
下面是我的函数和带有按钮的部分html代码:

function nextPage() {
  window.location.href = "yes.html";
}

function moveButton() {
  var x = Math.random() * (window.innerWidth - document.getElementById('noButton').offsetWidth);
  var y = Math.random() * (window.innerHeight - document.getElementById('noButton').offsetHeight);
  document.getElementById('noButton').style.left = `${x}px`;
  document.getElementById('noButton').style.top = `${y}px`;
}

个字符

8wigbo56

8wigbo561#

这个问题是因为按钮的位置是相对的,所以它们不能移动到DOM中的任何位置。要做到这一点,你需要设置position: absolute
还要注意的是,你的代码可以通过将对元素的引用放在你重用的变量中来改进,而不是重复调用DOM,这相对来说非常慢。
此外,更好的做法是在JS中绑定事件处理程序,并避免在HTML中使用onX事件属性。
最后,mouseover事件在鼠标移动到元素上的每个像素上触发一次。对于这个用例,mouseenter是一个更合适的事件。
下面是一个实现了上述更改的工作示例:

const yesButton = document.querySelector('#yesButton');
const noButton = document.querySelector('#noButton');

const moveNoButton = () => {
  var x = Math.random() * (window.innerWidth - noButton.offsetWidth);
  var y = Math.random() * (window.innerHeight - noButton.offsetHeight);

  noButton.style.position = 'absolute';
  noButton.style.left = `${x}px`;
  noButton.style.top = `${y}px`;
}

yesButton.addEventListener('click', () => {
  window.location.assign('yes.html');
})

noButton.addEventListener('click', moveNoButton);
noButton.addEventListener('mouseenter', moveNoButton);

个字符

相关问题