适配电脑的网站实现移动端访问提示功能(含JS、HTML开发需求)
Got it, let's tackle this problem. Since your site relies on mouse hover/leave interactions that don't translate well to touch devices, we can detect touch-enabled devices and show a friendly message to those users. Here's a clean, user-friendly implementation:
HTML Code
First, add the warning element to your page (it'll stay hidden by default until we trigger it):
<!-- Mobile Warning Banner --> <div id="mobile-warning" style="display: none; position: fixed; top: 0; left: 0; width: 100%; background: #ffd166; padding: 1rem; text-align: center; z-index: 9999; font-family: Arial, sans-serif;"> This Website has a better look with a Computer <button onclick="hideMobileWarning()" style="margin-left: 1rem; padding: 0.5rem 1rem; border: none; border-radius: 4px; background: #073b4c; color: white; cursor: pointer;">Got it</button> </div>
JavaScript Code
Add this script (either in a <script> tag at the end of your <body> or an external JS file) to handle device detection and warning display:
// Detect if the device supports touch input function isTouchDevice() { return (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); } // Show warning on page load if it's a touch device window.addEventListener('DOMContentLoaded', function() { const warningEl = document.getElementById('mobile-warning'); // Skip if user already dismissed the warning before if (isTouchDevice() && !document.cookie.includes('mobileWarningDismissed=true')) { warningEl.style.display = 'block'; } }); // Let users dismiss the warning function hideMobileWarning() { document.getElementById('mobile-warning').style.display = 'none'; // Set a cookie so the user doesn't see the message again for 30 days document.cookie = "mobileWarningDismissed=true; max-age=2592000; path=/"; }
Quick Breakdown
- Reliable Touch Detection: The
isTouchDevice()function uses multiple checks to cover all touch-enabled devices (phones, tablets, even touch-screen laptops if you want—you can adjust this if you only want to target small-screen mobiles). - User-Friendly Banner: The fixed top position ensures users can't miss the message, and the "Got it" button lets them dismiss it when ready.
- Cookie Persistence: The cookie logic prevents the warning from popping up every time the user visits, which keeps the experience smooth.
Feel free to tweak the CSS styles (colors, font, position) to match your site's design—just move the inline styles to your external stylesheet for cleaner code if you prefer.
内容的提问来源于stack exchange,提问作者Shon Max

