如何在不依赖第三方组件的情况下检测浏览器对Drag and Drop(DnD)、Touch及BoxShadow的支持?
Great question! Ditching Modernizr is totally doable with native JavaScript checks that are more reliable than those 8-10 year-old snippets you found. Let’s break down each feature with tested, up-to-date methods:
1. Drag and Drop (DnD) Support
Older methods that only check for the draggable property fall short because some browsers expose the property but don’t fully implement DnD events, or have quirks (looking at you, older Safari versions). Here’s a robust check that verifies both property and event support, plus handles edge cases:
function supportsDragAndDrop() { const testElement = document.createElement('div'); // Check core draggable attribute and DnD event support const hasDraggableAttr = 'draggable' in testElement; const hasDnDEvents = ('ondragstart' in testElement) && ('ondragend' in testElement); // Special handling for Safari, which had draggable property bugs in past versions const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); if (isSafari) { testElement.draggable = true; return testElement.draggable === true; } return hasDraggableAttr && hasDnDEvents; }
This method ensures the browser doesn’t just have the draggable property, but can actually handle the full DnD event lifecycle.
2. Touch Support
Detecting touch isn’t as tricky as it seems—you just need to avoid relying solely on ontouchstart (which some desktop browsers simulate). Instead, use modern APIs that check for actual hardware support:
function supportsTouch() { // Most reliable modern check: hardware touch point count if ('maxTouchPoints' in navigator) { return navigator.maxTouchPoints > 0; } // Fallback to media query for devices with coarse (touch) pointers const touchMediaQuery = window.matchMedia('(pointer: coarse)'); if (touchMediaQuery.matches) { return true; } // Final fallback for older browsers (may include simulated touch) return 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch); }
maxTouchPoints is the gold standard here because it directly reflects whether the device has touch hardware, not just if the browser can simulate touch events.
3. BoxShadow Support
This one’s straightforward—CSS property support can be checked directly on an element’s style object, including prefixes for older browsers if needed:
function supportsBoxShadow() { const testElement = document.createElement('div'); // Check for standard unprefixed property (modern browsers) if ('boxShadow' in testElement.style) { return true; } // Check for vendor-prefixed versions (for legacy browsers like IE9-10) const vendorPrefixes = ['Webkit', 'Moz', 'O', 'ms']; for (const prefix of vendorPrefixes) { if (`${prefix}BoxShadow` in testElement.style) { return true; } } return false; }
All modern browsers support the unprefixed boxShadow property, so the prefix check is optional if you don’t need to support browsers older than IE11.
内容的提问来源于stack exchange,提问作者sunil20000

