隐藏/显示一个按钮不在同一div中的div



我使用元素为我的wordpress网站,我希望有一个按钮在第一个div(节),控制如果第二个和单独的div(节)显示与否。我试过使用复选框hack,但它只工作,如果复选框是在div作为内容https://css-tricks.com/the-checkbox-hack/

是否有使用CSS甚至javascript的解决方案?如果你建议我使用javascript,我会把我的function。php文件作为javascript的初学者,你能把我要实现的所有函数写进我的function。php文件吗

意思是:

<div>button</div> <div>content to show and hide on click on the button</div>

最诚挚的问候,克莱门特

你可以使用Jquery:

1-为DIV添加id

<div id = "btn_show"> button </div> <div id = "show"> content to show and hide on click on the button </div>

2-调用jquery显示

$("#btn_show").click(function(){
$("#show").show();
//or
$("#show").hide();
});
你可以用CDN 调用它
<script src="https://code.jquery.com/jquery-3.6.0.js"</script>

在没有任何库的javascript中,这可能很容易,但你需要在你的div和按钮上放一个id。

<div id="myButton">button</div> 
<div id="myDiv">
content to show and hide on click on the button
</div>

然后你只需添加这样一个脚本部分:(它只需要在你的div和DOM中的按钮之后)

<script>
var myDiv = document.getElementById('myDiv');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', e => {
myDiv.classList.toggle('visible'):
});
</script>

最后,你需要一个这样的css:

.visible {
display: none;
}

谢谢大家的回答!下面是我使用的:

<button onclick="myFunctionopenclose()">Click Me</button>
<div id="myDiv" style="display:none;">content to hide and show</div>
<script> function myFunctionopenclose() {
var x = document.getElementById("myDiv");
if (x.style.display === "block") {
x.style.display = "none"; } 
else {
x.style.display = "block";}} 

最诚挚的问候,克莱门特

最新更新