CSS 点击触发声音是一种带有交互效果的设计,可以让按钮点击时发出声音,增加用户体验和满足视听需求。下面是一个实现这种效果的 CSS 代码:
button { background-color: #333; color: #fff; border: none; padding: 10px; cursor: pointer; position: relative; overflow: hidden; } button::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; background-color: rgba(255, 255, 255, 0.3); border-radius: 50%; transition: all 0.3s ease; z-index: -1; } button:hover::before { width: 150%; height: 150%; } button:focus::before { width: 250%; height: 250%; } button:focus::after { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 20px; height: 20px; background-color: #fff; border-radius: 50%; box-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #fff; animation: pulse 1s ease-out; z-index: 1; /* 使用 HTML5 音频元素实现点击声音 */ pointer-events: none; } @keyframes pulse { 0% { opacity: 1; transform: scale(0); } 100% { opacity: 0; transform: scale(2); } }
在这段代码中,我们通过伪元素 ::before
和 ::after
实现了按钮的样式效果,并借助 transition
和 animation
属性给用户带来了视觉上的愉悦感受。
要实现点击触发声音,我们可以在 button:focus::after
伪元素中使用 HTML5 音频元素实现。通过设置 pointer-events: none;
,我们可以让该元素的点击事件不会对元素本身产生影响。而在 JavaScript 中,我们可以通过给按钮绑定 click
事件来触发音频的播放:
const button = document.querySelector('button'); const audio = new Audio('click-sound.mp3'); button.addEventListener('click', () => { audio.play(); } );
这样在点击按钮时,就能同时听到声音的效果了。