gpt4 book ai didi

javascript - 使动态生成的按钮默认隐藏

转载 作者:行者123 更新时间:2023-11-30 14:29:36 25 4
gpt4 key购买 nike

我正在制作一个网页,我所拥有的是我从我的数据库中获取名称,然后将其制作成按钮。这些按钮有一个 onclick 功能,效果很好(它隐藏了我按下的任何按钮的内容),但默认情况下所有内容都是可见的,这不是我想要的。

'display: none' 出于某种原因对我不起作用。我在这里遗漏了什么吗?

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;
}

最佳答案

CSS 样式规则对 JavaScript 不可见,除非您将它们应用到 JavaScript 中。您需要使用 getComputedStyle()获取规则值:

var style = window.getComputedStyle(x, null).getPropertyValue("display");

if (style == 'none') {
x.style.display = "block";
} else {
x.style.display = 'none';
}

关于javascript - 使动态生成的按钮默认隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51413603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com