如何通过内部元素隐藏Div?按钮JS与Checkbox方案均失效求解决
问题解决:通过Div内部元素隐藏父Div
你尝试的两种方案都存在语法或逻辑错误,下面逐个修正:
一、Checkbox方案失效原因及修正
你的CSS选择器#hide_div:checked~#out_box用了兄弟选择器,但#hide_div是#out_box的子元素,并非同级兄弟节点,所以这个选择器完全无法生效。
如果要保留Checkbox在Div内部,需要结合JS实现逻辑;若调整结构把Checkbox移到Div外则不符合你“内部元素”的需求。以下是内部Checkbox结合JS的可行方案:
#out_box{ background: rgba(0,0,20,0.56); height:30vh; width:20vw; }
<div id='out_box'> <input type='checkbox' id='hide_div'> <label for='hide_div'>ChkHideDiv</label> </div> <script> const checkbox = document.getElementById('hide_div'); const outBox = document.getElementById('out_box'); checkbox.addEventListener('change', function() { outBox.style.display = this.checked ? 'none' : 'block'; }); </script>
二、按钮JS方案失效原因及修正
你的代码存在3个关键错误:
- 按钮HTML语法错误:
id='hidebybtn>缺少闭合引号,且按钮标签未闭合(<button>未写</button>) - PHP的
isset($_GET['hidebybtn'])判断完全多余,普通按钮点击不会触发GET请求,JS代码不需要包裹在该判断内 - JS语法错误:
btn.onclick( function (){ ... );应为btn.onclick = function() { ... };,且函数括号未闭合
修正后的按钮方案代码:
#out_box{ background: rgba(0,0,20,0.56); height:30vh; width:20vw; }
<div id='out_box'> <button type='button' id='hidebybtn'>BtnHideDiv</button> </div> <script> const targetdiv = document.getElementById("out_box"); const btn = document.getElementById("hidebybtn"); btn.onclick = function() { targetdiv.style.display = "none"; }; </script>
完整可运行代码(整合两种方案)
<style> #out_box{ background: rgba(0,0,20,0.56); height:30vh; width:20vw; padding: 10px; } </style> <html> <body> <?php echo "<div id='out_box'> <button type='button' id='hidebybtn'>BtnHideDiv</button> <br><br> <input type='checkbox' id='hide_div'> <label for='hide_div'>ChkHideDiv</label> </div>"; ?> <script> // 按钮隐藏逻辑 const targetdiv = document.getElementById("out_box"); const btn = document.getElementById("hidebybtn"); btn.onclick = function() { targetdiv.style.display = "none"; }; // Checkbox隐藏逻辑 const checkbox = document.getElementById('hide_div'); checkbox.addEventListener('change', function() { targetdiv.style.display = this.checked ? 'none' : 'block'; }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者colts moe
相关产品推荐
相关产品推荐

