我正在制作一个网页,我所拥有的是从数据库中获取名称,然后将其制成按钮。这些按钮具有onclick函数,可以很好地工作(它隐藏了我按下的任何按钮的内容),但是默认情况下所有内容都是可见的,这不是我想要的。
“显示:无”由于某种原因对我不起作用。我在这里想念东西吗?
HTML:
<h3>Select Class: </h3>
<ul>
<?php
$count = 0;
while($getName = mysqli_fetch_assoc($un)){
$name = $record['Name'];
$count++;
echo "<div id = 'classes'><button class = 'classes' onclick = 'toggleCont($count)'>".$name."</button></div>";
echo "<div id = '$count'><div class = 'content'>"DETAILS HERE"</div></div>";
}
?>
</ul>
CSS
#classes{
padding: 20px;
margin-top: 20px;
width: auto;
height: 10%;
background-color:#d3dded;
overflow: hidden;
}
.classes {
padding: 20px;
border: none;
width: 100%;
background-color:#d3dded;
}
.content{
width: auto;
background-color: grey;
height: 25%;
display: block;
}
最后,javascript部分:
<body>
<script>
function toggleCont(name){
var x = document.getElementById(name);
if (x.style.display == 'none'){
x.style.display = "block";
}
else{
x.style.display = 'none';
}
}
</script>
已编辑代码,但仍无法正常工作
<script>
function toggleCont(name){
var x = document.getElementById(name);
var style = window.getComputedStyle(x, null).getPropertyValue("display");
if (style == 'none') {
x.style.display = "block";
} else {
x.style.display = 'none';
}
}
</script>
<?php
$count = 0;
while($record = mysqli_fetch_assoc($un)){
$count++;
$class = 'content'.$count;
echo "<div class = 'btnclasses'><button class = 'classes' onclick = 'toggleCont($class)'>".$record['un']."</button></div>";
echo "<div id = '$class' class = 'content'>".$record['un']."</div>";
}
?>
css
.btnclasses{
padding: 20px;
margin-top: 20px;
width: auto;
height: 10%;
background-color:#d3dded;
overflow: hidden;
}
.classes {
padding: 20px;
border: none;
width: 100%;
background-color:#d3dded;
}
.content{
width: auto;
background-color: grey;
height: 25%;
display: none;
}
答案 0 :(得分:2)
CSS样式规则在JavaScript上应用之前是不可见的。您需要使用getComputedStyle()
来获取规则值:
var style = window.getComputedStyle(x, null).getPropertyValue("display");
if (style == 'none') {
x.style.display = "block";
} else {
x.style.display = 'none';
}