如何实现点击屏幕非目标Div区域恢复页面初始状态?
Solution: Trigger Reverse Action on Any Screen Click
Got it, let's tweak your code so you can click anywhere on the screen to revert back to the initial state, instead of being limited to the button. Here's the adjusted code with clear explanations:
$(".readNowbutton").click(readNow); function readNow() { // Animate elements to the "expanded" state $(".bookBox-1, .bookBox-2, .bookBox-3, .bookBox-4, .bookBox-5").animate({ top: "800" }); $(".selectStoryBox").animate({ right: "2800" }); $(".bookDescription-1").delay(1000).animate({ top: "120" }); $("hr").slideToggle(); // Clean up old event listeners to avoid duplicate triggers $(".readNowbutton").unbind("click"); $(document).unbind("click", readNowReverse); // Bind reverse action to both the button AND any screen click $(".readNowbutton").click(readNowReverse); $(document).click(readNowReverse); } // Reverts page to its initial state function readNowReverse(event) { // Stop event bubbling to prevent double-triggering the action event.stopPropagation(); // Animate elements back to their original positions $(".bookBox-1, .bookBox-2, .bookBox-3, .bookBox-4, .bookBox-5").animate({ top: "0" }); $(".bookDescription-1").animate({ top: "0" }); $(".selectStoryBox").animate({ right: "2800" }); $("hr").slideToggle(); // Reset event listeners to restore the original workflow $(document).unbind("click", readNowReverse); $(".readNowbutton").unbind("click"); $(".readNowbutton").click(readNow); }
Key Changes Breakdown:
- Global Click Binding: We added a click listener to the entire
documentin thereadNowfunction — this is what lets users click anywhere to trigger the revert action. - Event Cleanup: We unbind old listeners before adding new ones to avoid multiple overlapping triggers (a common issue if users click the button multiple times).
- Bubbling Prevention:
event.stopPropagation()ensures that clicking the button (or animated elements) doesn't trigger the document click event twice. - Cycle Reset: After reverting, we unbind the global click listener and restore the button's original
readNowfunctionality so the interaction cycle can repeat.
内容的提问来源于stack exchange,提问作者Delroy Brown
相关产品推荐
相关产品推荐

