我正在寻找一种改进这段代码的方法,因为我拒绝相信没有更好的方法。
这是HTML:
<div id = "panel1" onclick = "Function1()">
First panel
</div>
<div id = "panel2" onclick = "Function2()">
Second panel
</div>
<div id = "panel3" onclick = "Function3()">
Third panel
</div>
这是Javascript:
function Function1() {
document.getElementById('panel1').style.display = "flex";
document.getElementById('panel2').style.display = "none";
document.getElementById('panel3').style.display = "none";
}
function Function1() {
document.getElementById('panel1').style.display = "none";
document.getElementById('panel2').style.display = "flex";
document.getElementById('panel3').style.display = "none";
}
function Function1() {
document.getElementById('panel1').style.display = "none";
document.getElementById('panel2').style.display = "none";
document.getElementById('panel3').style.display = "flex";
}
它应该改变块的显示样式。
JQuery fadeIn和fadeOut可以是一个选项,更平滑的过渡。文档http://api.jquery.com/fadein/
$( "#panel1" ).fadeIn( "slow", function() {
// Animation complete
});
$( "#panel1" ).fadeOut( "slow", function() {
// Animation complete
});
function Function1() {
$( "#panel1" ).fadeOut( "slow", function() {
// Animation complete.
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "panel1" onclick = "Function1()">
First panel
</div>
<div id = "panel2" onclick = "Function1()">
Second panel
</div>
我已经为此添加了切换功能,因为我认为你会想要它。
toggle = () => {
let allPanels = document.querySelectorAll("div[id^='panel']");
if (event.target.style.display === 'flex') { // Show all
allPanels.forEach(e => {
e.style.display = "block";
});
} else { // Hide some
let curId = event.target.id;
allPanels.forEach(e => {
if (e.id === curId) {
e.style.display = "flex";
} else {
e.style.display = "none";
}
});
}
};
<div id="panel1" onclick="toggle()">
First panel
</div>
<div id="panel2" onclick="toggle()">
Second panel
</div>
<div id="panel3" onclick="toggle()">
Third panel
</div>
如果您不希望它可以切换:
toggle = () => {
let allPanels = document.querySelectorAll("div[id^='panel']");
let curId = event.target.id;
allPanels.forEach(e => {
if (e.id === curId) {
e.style.display = "flex";
} else {
e.style.display = "none";
}
});
};
<div id="panel1" onclick="toggle()">
First panel
</div>
<div id="panel2" onclick="toggle()">
Second panel
</div>
<div id="panel3" onclick="toggle()">
Third panel
</div>
希望这可以帮助,