如何实现点击按钮两次时1秒内将元素Margin-Left重置为0?
如何实现点击按钮两次时1秒内将元素Margin-Left重置为0?
我来帮你搞定这个问题!你的需求很清晰:第一次点击按钮让盒子用300秒慢慢“飞远”,第二次点击让它1秒快速“回家”。现在的代码问题在于过渡时长的切换没有和点击动作对应上,我们来做针对性修改,改动很小就能实现需求:
调整后的代码
JavaScript部分
var clicked1 = 0; const btn = document.getElementById("blast") const $box = $(".box"); // 提前缓存DOM元素,提升性能 function screen() { if (clicked1 === 0) { // 第一次点击:触发飞远动作,用300秒过渡 $box.css('transition-duration', '300s').toggleClass("boxxy", 0); btn.textContent = "RETURN HOME"; clicked1 = 1; } else { // 第二次点击:触发返回动作,用1秒快速过渡 $box.css('transition-duration', '1s').toggleClass("boxxy", 0); btn.textContent = "FLY AWAY"; clicked1 = 0; // 过渡结束后,把过渡时长恢复为300秒,方便下次飞远 $box.one('transitionend', function() { $box.css('transition-duration', '300s'); }); } }
CSS部分
body { background-color: #6A6A6A; } html, body { height: 100%; } .boxxy { margin-left: -20000px; /* 这里不再写固定过渡时长,由JS动态控制 */ } .box { position: fixed; top: 0px; left: 0px; width: 20000px; height: calc(100% - 100px); overflow: hidden; transition-timing-function: linear; transition-duration: 300s; /* 默认飞远的过渡时长 */ z-index: 5; } .box img { height: 100%; width: 100%; } .linksbox { position: fixed; bottom: 0px; left: 0px; width: 100%; height: 100px; text-align: center; background-color: #000000; font-size: 25px; color: #AEBC1F; }
HTML部分(保持不变)
<div id="box" class="box"> <img src="https://tim-school.com/codepen/2dgame/wall.png" alt="" /> </div> <div class="linksbox"> <button onClick="screen()" id="blast">FLY AWAY</button> </div> <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
改动说明
- 动态控制过渡时长:飞远时用300秒过渡,返回时临时切换为1秒,过渡结束后再恢复默认时长,确保每次动作的过渡速度符合需求。
- 缓存DOM元素:提前把
.box元素缓存起来,避免每次点击都重新查询DOM,提升性能。 - 简化状态切换逻辑:去掉了冗余的
else if判断,直接用else更简洁,同时用严格相等===替代==,避免隐式类型转换问题。
这样调整后,第一次点击按钮,盒子会用300秒慢慢移走;第二次点击,盒子会立刻以1秒的速度回归原位,完全符合你的需求~
备注:内容来源于stack exchange,提问作者Timbukto
相关产品推荐
相关产品推荐

