Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Có thể tùy chỉnh giao diện thẻ <audio> HTML5 không?

Có. Thẻ <audio> HTML5 có thể được tùy chỉnh giao diện (style).

Hai cách tiếp cận

Cách 1: Sử dụng controls mặc định (dễ nhưng ít tùy biến)

<audio controls src="music.mp3"></audio>
  • Trình duyệt hiển thị player tích hợp (play, pause, volume, seek bar).
  • Giao diện khác nhau trên mỗi trình duyệt (Chrome, Firefox, Safari...).
  • Khó can thiệp CSS vào bên trong shadow DOM của player.

Cách 2: Tự xây dựng UI tùy chỉnh (linh hoạt hoàn toàn) - Khuyên dùng

Loại bỏ thuộc tính controls, tự tạo nút bấm và điều khiển bằng JavaScript:

<audio id="player" src="kalimba.mp3"></audio>
<div class="audio-controls">
  <button onclick="document.getElementById('player').play()">Play</button>
  <button onclick="document.getElementById('player').pause()">Pause</button>
  <button onclick="document.getElementById('player').volume = Math.min(1, document.getElementById('player').volume + 0.2)">Vol+</button>
  <button onclick="document.getElementById('player').volume = Math.max(0, document.getElementById('player').volume - 0.2)">Vol-</button>
  <input type="range" min="0" max="1" step="0.1" value="1" 
         oninput="document.getElementById('player').volume = this.value">
  <progress id="seek" value="0" max="1"></progress>
</div>

CSS tùy chỉnh

.audio-controls button {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.audio-controls button:hover { background: #0056b3; }
#seek { width: 200px; }

JavaScript nâng cao (đồng bộ UI)

const audio = document.getElementById('player');
const seek = document.getElementById('seek');

audio.addEventListener('timeupdate', () => {
  seek.value = audio.currentTime;
  seek.max = audio.duration;
});

seek.addEventListener('input', () => {
  audio.currentTime = seek.value;
});

Thư viện sẵn có

  • MediaElement.js - Player nhất quán cross-browser.
  • Plyr - Nhẹ, hiện đại, accessible.
  • Video.js - Hỗ trợ cả video & audio, plugin phong phú.