切换toggle开关时transition过渡动画无法触发问题求助
问题根因
CSS 过渡动画transition无法对display属性生效,且设置为display: none的元素会被浏览器从渲染树中直接移除,没有初始过渡状态,因此直接切换display属性无法触发过渡效果。
修改方案
1. 调整CSS样式
移除原有切换display的逻辑,改用opacity、宽高、visibility属性控制元素显隐,新增激活状态类:
.radius-of-distraction { background-color: rgba(16,112,142,.4); border-radius: 50%; left: 46%; /* 初始隐藏状态 */ width: 0; padding-bottom: 0; opacity: 0; visibility: hidden; pointer-events: none; position: absolute; top: 51%; transform: translate(-50%,-50%); /* 统一设置过渡属性,修复原有属性拼写错误 */ transition: all .3s ease-in; } /* 激活显示状态 */ .radius-of-distraction.active { width: 40%; padding-bottom: 40%; opacity: 1; visibility: visible; pointer-events: auto; }
原有CSS中- webkit-transition-property存在多余空格的拼写错误,建议直接删除该属性,使用上述统一的transition配置即可。
2. 调整JS逻辑
不再切换display属性,改为控制元素的active类切换:
$("#customSwitch1").on('change', function() { const $bubble = $('#bubble'); if ($(this).is(':checked')) { $(this).attr('value', 'true'); $bubble.addClass('active'); } else { $(this).attr('value', 'false'); $bubble.removeClass('active'); } });
修改后即可实现开关开启时蓝色圆圈从小到大平滑出现,开关关闭时圆圈从大到小平滑消失的效果。
内容的提问来源于stack exchange,提问作者bigbrotherx
相关产品推荐
相关产品推荐

