-3 html javascript css
脚本不起作用.当我点击"nombreDeLista"时,我想用display属性显示"tiposDeFrutas".我还添加了CSS文档.
.tiposDeFrutas {
display: none;
}Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<title>Pruebas HTML</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel=StyleSheet href="newcss.css" type="text/css" media=screen>
<script>
document.onload = function() {
document.getElementById("nombreDeLista").onclick = function() {
document.getElementsByClassName("tiposDeFrutas").style.display = "block";
};
};
</script>
</head>
<body>
<div id="nombreDeLista">Frutas</div>
<div class="tiposDeFrutas">Pera</div>
<div class="tiposDeFrutas">Limón</div>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
document.getElementsByClassName("tiposDeFrutas")将返回一个对象数组,您可以使用[0]以下方法定位第一个对象:
document.getElementsByClassName("tiposDeFrutas")[0].style.display = "block";
Run Code Online (Sandbox Code Playgroud)
如果要显示所有元素,可以使用for循环遍历它们.
document.getElementById("nombreDeLista").addEventListener('click', showAll, false);
function showAll() {
var tiposDeFrutas = document.getElementsByClassName("tiposDeFrutas");
for (var i = 0; i < tiposDeFrutas.length; i++) {
tiposDeFrutas[i].style.display = "block";
}
}Run Code Online (Sandbox Code Playgroud)
.tiposDeFrutas {
display: none;
}Run Code Online (Sandbox Code Playgroud)
<div id="nombreDeLista">Frutas</div>
<div class="tiposDeFrutas">Pera</div>
<div class="tiposDeFrutas">Limón</div>Run Code Online (Sandbox Code Playgroud)