必填结果:简单的JavaScript脚本,可重置(更改)多个div,例如图像幻灯片。自动和onButtonClick。
虽然脚本是自动运行的,但一切都会按预期进行,但是...如果按下了某些按钮:
计时功能“中断”,div面板不显示10秒钟,下注不同的时间。有时5秒,有时3秒,甚至1秒,并始终刷新。
我还不明白为什么,也许也是因为时间原因。有时没有显示div或同时显示所有
一个简短的代码示例(我添加了注释,我认为该行应该做的事情):
//about carousel
var panelAIndex = 0; //set default div
showAPanel(); // call function
$("#btn_about_1").on("click", function () {
panelAIndex = 0; // set div
showAPanel() // call function
});
$("#btn_about_2").on("click", function () {
panelAIndex = 1; // set div
showAPanel() // call function
});
function showAPanel() {
var timer = "10000"; // 10 seconds timer
var panelA = document.getElementsByClassName("about"); // get div's
var btn_A_primary = document.getElementById("btn_about_1"); // get first button
var btn_A_second = document.getElementById("btn_about_2"); // get second button
for (var i = 0; i < panelA.length; i++) {
panelA[i].style.display = "none"; // hide all div
}
panelAIndex++; // increse div id
if (panelAIndex > panelA.length) {
panelAIndex = 1
} // if last panel, reset to first
// change buttons
if (panelAIndex == 2) {
btn_A_primary.classList.remove("btn_primary");
btn_A_primary.classList.add("btn_second");
btn_A_second.classList.remove("btn_second");
btn_A_second.classList.add("btn_primary");
} else {
btn_A_second.classList.remove("btn_primary");
btn_A_second.classList.add("btn_second");
btn_A_primary.classList.remove("btn_second");
btn_A_primary.classList.add("btn_primary");
}
// show div
$(panelA[panelAIndex - 1]).fadeIn('slow');
// after 10 seconds call function again
setTimeout(showAPanel, timer);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="about">
<div id="about_image"></div>
<div class="about" id="about_1">
//couple paragraphs 1
</div>
<div class="about" id="about_2">
//couple paragraphs 2
</div>
<button class="btn_second" id="btn_about_2">BUTTON 2</button>
<button class="btn_primary" id="btn_about_1">BUTTON 1</button>
</section>