用HTML+CSS+JS实现在页面右侧悬浮浮动按钮,功能有:白天/黑夜模式转换,缩小字体,放大字体,返回顶部。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>浮动按钮组</title> <style> body { font-family: Arial, sans-serif; background-color: white; color: black; padding: 20px; transition: background-color 0.3s, color 0.3s; margin: 0; height: 2000px; } body.night-mode { background-color: #121212; color: white; } .floating-buttons { position: fixed; right: 20px; bottom: 20px; display: flex; flex-direction: column; gap: 10px; } .floating-buttons button { width: 40px; height: 40px; font-size: 20px; background-color: #333; color: white; border: none; border-radius: 5px; cursor: pointer; display: flex; justify-content: center; align-items: center; } .disabled { text-decoration: line-through; cursor: not-allowed; } </style> </head> <body> <div id="content"> <h1>页面标题</h1> <p>文本信息,wenbenxinxi。文本信息,wenbenxinxi。文本信息,wenbenxinxi。文本信息,wenbenxinxi。文本信息,wenbenxinxi。文本信息,wenbenxinxi。文本信息,wenbenxinxi。文本信息,wenbenxinxi。</p> </div> <div> <button id="toggle-mode">🌙</button> <button id="zoom-out">A</button> <button id="zoom-in">A</button> <button id="back-to-top">↑</button> </div> <script> const body = document.body; const toggleModeButton = document.getElementById('toggle-mode'); const zoomOutButton = document.getElementById('zoom-out'); const zoomInButton = document.getElementById('zoom-in'); const backToTopButton = document.getElementById('back-to-top'); const content = document.getElementById('content'); let scale; const browserWidth = window.innerWidth; if (browserWidth > 1600) { scale = 1.2; } else if (browserWidth > 1280) { scale = 1.1; } else { scale = 1; } content.style.transform = `scale(${scale})`; content.style.transformOrigin = 'top left'; toggleModeButton.addEventListener('click', function () { if (body.classList.contains('night-mode')) { body.classList.remove('night-mode'); this.textContent = '🌙'; } else { body.classList.add('night-mode'); this.textContent = '☀'; } }); zoomOutButton.addEventListener('click', function () { if (scale > 1) { scale -= 0.1; content.style.transform = `scale(${scale})`; if (scale === 1) { this.classList.add('disabled'); } zoomInButton.classList.remove('disabled'); } }); zoomInButton.addEventListener('click', function () { if (scale < 1.5) { scale += 0.1; content.style.transform = `scale(${scale})`; if (scale === 1.5) { this.classList.add('disabled'); } zoomOutButton.classList.remove('disabled'); } }); backToTopButton.addEventListener('click', function () { window.scrollTo({ top: 0, behavior: 'smooth' }); }); zoomOutButton.style.fontSize = '12px'; zoomOutButton.style.fontWeight = 'bold'; zoomInButton.style.fontSize = '18px'; zoomInButton.style.fontWeight = 'bold'; </script> </body> </html>
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。