<head>
<style>
.b1{
display:none;
visibility: none;
background-color:blue;}
</style>
</head>
<body>
<button class="offer-btn" onclick="openTab('b1');" type="button">DETAILS</button>
<div id="b1" class="containerTab" >
<span onclick="this.parentElement.style.display='none'" class="closebtn">×</span>
<h2>Box 1</h2>
<p>some text</p>
</div>
</body>
<script>
function openTab(tabName) {
var i, x;
x = document.getElementsByClassName("containerTab");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
}
</script>
我希望我的按钮在进入页面时关闭。我试着把剧本放在头部,但还是一样
这是我进入时的图片:https://i.stack.imgur.com/6cJ5X.png
当您查找ID选择器(#b1
(时,CSS会使用class选择符(.b1
(。
只需更换即可解决问题:
function openTab(tabName) {
var i, x;
x = document.getElementsByClassName("containerTab");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
}
#b1 {
display: none;
visibility: none;
background-color: blue;
}
<button class="offer-btn" onclick="openTab('b1');" type="button">DETAILS</button>
<div id="b1" class="containerTab">
<span onclick="this.parentElement.style.display='none'" class="closebtn">×</span>
<h2>Box 1</h2>
<p>some text</p>
</div>
请注意,如果您愿意,也可以使用.containerTab
来代替#b1
。
还要注意的是,您最好使用Unobtrusive JavaScript,而不是内联事件处理程序,尽管这对于解决您的问题不是必需的。