Case:27(ESC)在Microsoft Edge中无法正常工作问题求助
Hey there! Let's figure out why your ESC key (keyCode 27) isn't working in Microsoft Edge and how to get it to trigger the #messagebtn page jump properly across all browsers.
Possible Reasons for Edge Failure
- Edge has subtle differences in handling the legacy
keyCodeproperty compared to other browsers. Modern standards now favor usingkeyorcodeattributes for more reliable key detection. - Edge's default ESC key behavior (like closing modals or triggering tab exit prompts) might be overriding your custom event.
- Outdated event binding methods (e.g., inline
onkeydown) can have compatibility issues with Edge's modern event handling system.
Edge-Compliant Solution Code
Here are two robust approaches that work seamlessly in Edge and all other major browsers:
Approach 1: Use Standard key Property (Recommended)
This method uses the most modern and readable way to detect the Escape key:
document.addEventListener('keydown', function(e) { // Directly check the key name for clarity and compatibility if (e.key === 'Escape') { e.preventDefault(); // Block Edge's default ESC actions (e.g., modal close) const messageBtn = document.getElementById('messagebtn'); if (messageBtn) { // Choose the action that matches your #messagebtn's function: // Option 1: Simulate a click on the button messageBtn.click(); // Option 2: Jump directly to the anchor if it's a link // window.location.href = messageBtn.href; } } });
Approach 2: Cross-Browser Compatibility Fallback
If you need to support older browsers alongside Edge, you can check multiple key properties:
document.addEventListener('keydown', function(e) { const isEscapePressed = e.key === 'Escape' || e.keyCode === 27 || e.code === 'Escape'; if (isEscapePressed) { e.preventDefault(); const messageBtn = document.getElementById('messagebtn'); if (messageBtn) { // Adjust based on your button's intended behavior window.location = '#messagebtn'; // For anchor jump // OR messageBtn.click(); For button click trigger } } });
Quick Checks to Ensure Success
- Make sure your script runs after the DOM is fully loaded to avoid targeting non-existent elements:
document.addEventListener('DOMContentLoaded', function() { // Place the key event listener code here });
- Verify no other scripts are blocking the ESC key event with
e.stopPropagation()ore.preventDefault()before your code runs.
This should resolve the Edge-specific issue and keep your functionality working across all browsers!
内容的提问来源于stack exchange,提问作者user9311312
相关产品推荐
相关产品推荐

