CSS中的div为何导致onclick事件失效?
问题:金字塔布局中仅第一个Modal可触发,其余点击失效
我按照教程用CSS的div制作了HTML金字塔,但onclick事件只有第一个Modal能触发,其余均失效。删除CSS中的div样式会导致页面布局混乱,怀疑问题出在该CSS div上,求修复。
现有代码:
JavaScript
function showpyramid() { var elements = document.querySelectorAll('.triangle'); elements.forEach(function(element) { element.classList.toggle('hidden'); }); } function Modal1() { $("#Modal1").modal("show"); } function Modal2() { $("#Modal2").modal("show"); }
CSS
.triangle div { position: absolute; top: 0; background: red; width: 100%; height: 80px; margin: 0 auto; color: white; line-height: 100px; text-align: center; font-size: 0.9em; color: red; transition: ease 10s; color: black; }
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> <h1>The Pyramid of Pain</h1> <button class="button" onclick="showpyramid()">Show Pyramid</button> <div class="hidden triangle"> <div onclick="Modal1()">TTPS</div> <div onclick="Modal2()">Tools</div> <div class="network">Network/Host Artifacts</div> <div class="domain">Domain Names</div> <div class="ip">IP Addresses</div> <div class="hash">Hash Values</div> </div>
问题原因
核心问题是你给.triangle div设置了position: absolute和top: 0,这会让所有子div都定位在父容器的左上角,完全重叠在一起。点击时只有最上层的第一个div("TTPS")能接收点击事件,下方的div被完全遮挡,自然无法触发对应的Modal。
修复方案
修改CSS,让子div垂直排列且不重叠,同时保持金字塔的布局形状:
修改后的CSS
/* 父容器设置相对定位,作为子元素绝对定位的参照 */ .triangle { position: relative; width: 600px; margin: 20px auto; min-height: 530px; /* 适配所有子div的总高度 */ } .triangle div { position: absolute; background: red; color: black; line-height: 80px; text-align: center; font-size: 0.9em; height: 80px; left: 50%; transform: translateX(-50%); /* 水平居中 */ transition: ease 0.3s; /* 缩短过渡时间,更实用 */ cursor: pointer; /* 提示用户该元素可点击 */ } /* 为每个层级设置递减的宽度和递增的top值,形成金字塔 */ .triangle div:nth-child(1) { width: 90%; top: 0; } .triangle div:nth-child(2) { width: 80%; top: 90px; /* 上一个div高度 + 10px间距 */ } .triangle div:nth-child(3) { width: 70%; top: 180px; } .triangle div:nth-child(4) { width: 60%; top: 270px; } .triangle div:nth-child(5) { width: 50%; top: 360px; } .triangle div:nth-child(6) { width: 40%; top: 450px; } .hidden { display: none; }
可选优化:简化JS事件处理
如果后续要添加更多层级,不用逐个写Modal函数,可以用事件委托统一处理:
function showpyramid() { document.querySelector('.triangle').classList.toggle('hidden'); } // 事件委托:父元素监听点击,判断触发源 document.querySelector('.triangle').addEventListener('click', function(e) { const childIndex = Array.from(this.children).indexOf(e.target); if (childIndex !== -1) { const modalId = `Modal${childIndex + 1}`; $(`#${modalId}`).modal('show'); } });
内容的提问来源于stack exchange,提问作者Paul2021
相关产品推荐
相关产品推荐

