如何创建躲避鼠标指针的按钮?我的实现代码为何无响应?
问题原因
按钮默认是position: static定位,这种定位模式下left、top属性完全不生效,所以你设置的坐标根本无法改变按钮位置。
修复方案
给目标按钮添加position: absolute(或fixed)定位,让left和top属性能正常控制元素位置。同时可以优化代码,减少重复的DOM查询操作。
修改后的完整代码
CSS
.button { /* 添加绝对定位,让left/top属性生效 */ position: absolute; }
JavaScript
function nextPage() { window.location.href = "yes.html"; } function moveButton() { // 仅查询一次DOM元素,避免重复查找损耗性能 const noBtn = document.getElementById('noButton'); const x = Math.random() * (window.innerWidth - noBtn.offsetWidth); const y = Math.random() * (window.innerHeight - noBtn.offsetHeight); noBtn.style.left = `${x}px`; noBtn.style.top = `${y}px`; }
HTML
<div class="buttons"> <button class="button" id="yesButton" onclick="nextPage()">Yes!</button> <button class="button" id="noButton" onmouseover="moveButton()" onclick="moveButton()">No...</button> </div>
如果希望按钮滚动页面时固定在视口,可把position: absolute换成position: fixed;若想让按钮相对于父容器定位,给父元素.buttons添加position: relative即可。
内容的提问来源于stack exchange,提问作者Michał Leśko
相关产品推荐
相关产品推荐

