如何防止快速点击时.fullsection元素出现抖动?
问题
使用jQuery开发页面时,慢速点击.fullsection元素功能正常,但快速点击(尤其是第四个元素)会出现抖动现象。通过添加/移除.active类改变元素宽度(用animate()时抖动更严重),尝试用is("animating")结合return false阻止动画期间点击,但无效。希望解决抖动或阻止动画期间的点击操作。
解决方案
1. 禁用动画期间的点击事件
利用CSS的pointer-events属性,在元素过渡动画期间设置为none,结束后恢复。结合jQuery监听transitionend事件控制状态,从根源避免快速点击触发重复操作。
2. 简化逻辑,避免数值判断误差
原代码通过宽度数值判断.active类的逻辑容易因过渡中的数值波动出错,直接通过类名判断更可靠,减少不必要的计算开销。
3. 初始化动画优化
将原初始化阶段的animate()动画替换为CSS过渡,避免jQuery动画的性能损耗,同时保持序列展开的效果。
修改后的代码
JavaScript
$(function() { const fullSection = $(".fullsection"); const container = $("#container"); // 初始化:非active元素先收缩再序列展开(用CSS过渡替代animate) fullSection.each(function(index, item) { if (!$(item).hasClass("active")) { $(item).css('height', '0%'); setTimeout(() => { $(item).css('height', '100%'); }, index * 150 + 500); } }); fullSection.click(function(event) { // 当前元素处于过渡状态时,直接终止操作 if ($(this).hasClass('transitioning')) return; // 点击已激活元素,不做操作 if ($(this).hasClass('active')) return; const $this = $(this); // 给所有元素添加过渡标记,禁用点击 fullSection.addClass('transitioning'); // 移除其他元素的激活状态 $this.siblings('.active').removeClass('active'); // 激活当前元素 $this.addClass('active'); // 监听过渡结束,移除过渡标记,恢复点击 $this.one('transitionend', function() { fullSection.removeClass('transitioning'); }); }); });
CSS
/* reset */ @import url("reset.css"); /* font-family: 'Abril Fatface', cursive; */ @import url('https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap'); /* global class */ body, html { width: 100%; height: 100%; } #container { width: 100%; height: 100%; -webkit-backface-visibility: hidden; } .fullsection { width: 5%; height: 100%; padding: 100px 0; /* 修正原代码的逗号语法错误 */ box-sizing: border-box; float: left; transition: all .3s ease-in-out; /* 统一过渡属性,避免拆分导致的抖动 */ } .active { width: 85%; } /* 过渡期间禁用点击 */ .transitioning { pointer-events: none; } .section_1 { background-color: tomato; } .section_2 { background-color: teal; } .section_3 { background-color: cornflowerblue; } .section_4 { background-color: slateblue; }
HTML
<div id="container"> <div class="fullsection section_1 active"></div> <div class="fullsection section_2"></div> <div class="fullsection section_3"></div> <div class="fullsection section_4"></div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
内容的提问来源于stack exchange,提问作者Art Vandelay
相关产品推荐
相关产品推荐

