我正在学习如何制作手风琴列表,并从www.w3schools.com找到以下代码(HTML,CSS和JS)。如果我在本地运行代码,作为一个.html文件,它按预期工作。但是,如果我将它分成三个文件,并将HTML和JS文件链接到我的HTML文件中,则下拉列表不起作用。我(非常)对Web开发很新,并且非常感谢我能为此获得任何解释!提前谢谢。
原始代码(全部在一个文档中):
<!DOCTYPE html>
<html>
<head>
<style>
button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
button.accordion.active, button.accordion:hover {
background-color: #ddd;
}
button.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
button.accordion.active:after {
content: "\2212";
}
div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
</style>
</head>
<body>
<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
<p>TEXT 1</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
<p>TEXT 2</p>
</div>
<button class="accordion">Section 3</button>
<div class="panel">
<p>TEXT 3</p>
</div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}
</script>
</body>
</html>
将CSS和JS链接为单独文件的HTML文件:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./mystyling.css">
<title>Page TItle</title>
</head>
<body>
<script src="./myjavascript.js"></script>
<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
<p>TEXT 1</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
<p>TEXT 2</p>
</div>
<button class="accordion">Section 3</button>
<div class="panel">
<p>TEXT 3</p>
</div>
</body>
</html>
我的JS和CSS文件只是将JS和CSS文件复制并粘贴到其他文件(分别保存为.js和.css)。
答案 0 :(得分:1)
您将此处的目录用作 <link rel="stylesheet" href="./mystyling.css">
。我猜这会导致所选目录出错。
<link rel="stylesheet" href="mystyling.css">
如果文件夹中的css文件使用<link rel="stylesheet" href="folder/mystyling.css">
对于js文件,最好把文件放在body标签的末尾
<script src="myjavascript.js"></script>
</body>
如果代码很小,那么尝试在脚本标签内的同一个文件上写
<script>
//Your code
</script>
答案 1 :(得分:0)
快速说明,您想要将身体的底部链接起来。您希望在JavaScript执行之前加载HTML:
<script src="./myjavascript.js"></script>
</body>
第二点,Mozilla Developer Network比W3学校更具信息性和可靠性。你想训练自己在W3上访问MDN。
您的js和css文件位于何处?我们也能看到那些代码吗?
要更有效地调试,请在浏览器中打开html文件,然后使用开发人员工具告诉我们您遇到的错误(如果有的话)。选项+命令+ j用于mac和control + shift + j在Windows上,或者只需右键单击inspect元素。