为何无法显示指定div?获取按钮尺寸/位置返回null求助
问题修复方案
1. 点击botao2按钮后heart元素不显示
CSS的display属性不存在visible这个有效值,div元素默认的显示值是block,修改setHeart函数即可:
function setHeart(element){ document.getElementById("botao").style.display = "none"; document.getElementById("botao2").style.display = "none"; document.getElementById("heart").style.display = "block"; // 替换visible为block }
2. 无法获取按钮宽高、设置位置无效
核心原因
- DOM元素没有
x/y属性,直接设置会返回null;按钮默认position: static,无法通过top/left定位 - 按钮样式中的
transform: translateY(-50%); top:50%;会干扰布局尺寸计算 - 使用
margin定位容易和父容器的flex布局冲突
修复代码
修改后的CSS(调整按钮样式)
.item { flex: 1; background: white; font-size: 1.5em; border-radius: 10px; width: 80px; height: 40px; border: none; color: red; position: relative; /* 添加相对定位,支持top/left调整位置 */ }
修改后的JS(调整获取尺寸和定位逻辑)
// 确保DOM加载完成后再执行相关操作 document.addEventListener('DOMContentLoaded', function() { // 初始化heart隐藏 document.getElementById("heart").style.display = "none"; }); function move(el){ let container = document.querySelector(".container-button"); // 使用getBoundingClientRect获取更准确的元素尺寸 const btnRect = el.getBoundingClientRect(); const containerRect = container.getBoundingClientRect(); const width = Math.ceil(btnRect.width); const height = Math.ceil(btnRect.height); const maxTop = Math.floor(containerRect.height - height); const maxLeft = Math.floor(containerRect.width - width); const changeTop = Math.floor(Math.random() * (maxTop + 1)); const changeLeft = Math.floor(Math.random() * (maxLeft + 1)); // 使用top/left定位(配合position: relative) el.style.top = changeTop + "px"; el.style.left = changeLeft + "px"; } function setHeart(element){ document.getElementById("botao").style.display = "none"; document.getElementById("botao2").style.display = "none"; document.getElementById("heart").style.display = "block"; }
修改后的HTML(移除内嵌的重复隐藏代码)
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css" type="text/css"> <script src="script.js"></script> </head> <body> <div class="container wrap"> <div class="container-title"> <h1>Quer sair comigo?</h1> </div> <div class="container-button"> <div class="heart" id="heart"></div> <div class="botao"> <button class="item" type="button" id="botao2" onclick="setHeart(this)">SIM</button> </div> <div class="botao"> <button type="button" class="item" id="botao" onmouseover="move(this)">NÃO</button> </div> </div> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Henrique Vital
相关产品推荐
相关产品推荐

