
本文旨在解决 CSS transition 在特定场景下需要点击两次才能生效的问题。通过分析问题代码,找出事件监听器重复绑定的原因,并提供修改后的代码示例,确保 transition 效果在第一次点击时就能正确触发。文章还将讨论如何避免类似问题的发生,以及如何优化 CSS transition 的性能。
问题描述中,CSS transition 效果需要点击按钮两次才能生效,这通常是由于事件监听器绑定方式不正确导致的。在提供的代码中,transitionEffect 函数内部使用了 addEventListener 来绑定点击事件。这意味着每次点击按钮,都会向该按钮添加一个新的点击事件监听器。
第一次点击时,绑定了事件监听器,但 transition 效果并没有立即执行。第二次点击时,之前绑定的事件监听器才开始生效,从而触发了 transition 效果。
正确的做法是在页面加载时,只绑定一次事件监听器。修改后的 transitionEffect 函数应该只包含 transition 相关的逻辑,而事件监听器的绑定应该在页面加载完成后执行。
立即学习“前端免费学习笔记(深入)”;
以下是修改后的代码示例:
JavaScript:
function transitionEffect() {
var layers = document.querySelectorAll(".bottom-layer");
for (const layer of layers) {
setTimeout(switchVisible, 900);
layer.classList.toggle("active");
}
}
function switchVisible() {
if (document.getElementById("main-cont")) {
if (document.getElementById("main-cont").style.display == "none") {
document.getElementById("main-cont").style.display = "block";
document.getElementById("overlay-cont").style.display = "none";
} else {
document.getElementById("main-cont").style.display = "none";
document.getElementById("overlay-cont").style.display = "block";
}
}
}
document.addEventListener("DOMContentLoaded", function() {
const button = document.querySelector("#last");
button.addEventListener("click", transitionEffect);
});HTML:
<button id="last"> click</button>
<div id="main-cont">
<h3>first page</h3>
</div>
<div id="overlay-cont">
<div class="row">
<div class="col-md-6 overlay-text" id="overlay-col">
<h1> next page</h1>
</div>
<div class="col-md-6" id="overlay-col">
</div>
</div>
</div>
<div class="transition-cont">
<div class="bottom-layer"></div>
<div class="bottom-layer bottom-layer--2"></div>
<div class="bottom-layer bottom-layer--3"></div>
</div>CSS (与原代码相同):
#overlay-cont {
display: none;
z-index: 1;
}
.bottom-layer {
position: absolute;
width: 100%;
height: 100%;
top: 100%;
left: 0;
bottom: auto;
right: auto;
background: #48466d;
transition: all 0.7s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.bottom-layer.active {
top: -100%;
}
.bottom-layer--2 {
background: #ecf3a3;
transition-delay: 0.12s;
}
.bottom-layer--3 {
background: #95a792;
transition-delay: 0.4s;
}代码解释:
为了避免类似问题的再次发生,需要注意以下几点:
CSS transition 可以为网页添加动画效果,但过度使用或不当使用可能会影响页面性能。以下是一些优化 CSS transition 性能的建议:
通过分析问题代码,我们可以发现 CSS transition 需要点击两次才能生效的原因是事件监听器被重复绑定。通过修改代码,确保事件监听器只绑定一次,可以解决这个问题。同时,我们也需要注意避免重复绑定事件监听器,并优化 CSS transition 的性能,以提高网页的整体性能。
以上就是CSS Transition 需要点击两次才能生效的解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号