API Tùy chọn người dùng

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

API Tùy chọn người dùng cho phép các tác giả trang web ghi đè theo chương trình các cài đặt truy vấn phương tiện liên quan đến tùy chọn người dùng.

Khái niệm và cách sử dụng

Các tác nhân người dùng hỗ trợ định nghĩa các giá trị cho truy vấn phương tiện CSS prefers-color-scheme, prefers-contrast, prefers-reduced-motion, prefers-reduced-transparencyprefers-reduced-data. Đối tượng PreferenceManager cung cấp quyền truy cập lập trình vào các tùy chọn này, cho phép tác giả trang lắng nghe các thay đổi tùy chọn và ghi đè chúng.

Ví dụ

Nút bật/tắt chế độ tối

Đoạn mã sau triển khai một nút bật/tắt chế độ tối tối giản.

HTML

HTML bao gồm một biểu mẫu chứa ba nút radio. Các nút radio này đặt trường color-scheme thành system, light hoặc dark.

html
<!doctype html>
<html lang="vi">
  <head>
    <meta name="color-scheme" content="light dark" />
  </head>
  <body>
    <form>
      <label>
        <input type="radio" name="color-scheme" value="light" />
        Light
      </label>
      <label>
        <input type="radio" name="color-scheme" value="dark" />
        Dark
      </label>
    </form>
  </body>
</html>

JavaScript

JavaScript đăng ký trình lắng nghe sự kiện thay đổi cho tất cả các phần tử có tên color-scheme. Nếu giá trị là system, trình xử lý sẽ xóa ghi đè bảng màu. Nếu không, nó sẽ yêu cầu ghi đè bảng màu với giá trị của phần tử đầu vào.

js
if (navigator.preferences) {
  const inputs = {
    light: document.querySelector('[name="color-scheme"][value="light"]'),
    dark: document.querySelector('[name="color-scheme"][value="dark"]'),
  };

  inputs[navigator.preferences.colorScheme.value].checked = true;

  inputs.light.addEventListener("change", () => {
    navigator.preferences.colorScheme.requestOverride("light");
  });
  inputs.dark.addEventListener("change", () => {
    navigator.preferences.colorScheme.requestOverride("dark");
  });

  navigator.preferences.colorScheme.addEventListener("change", () => {
    inputs[navigator.preferences.colorScheme.value].checked = true;
  });
} else {
  document.body.append(
    "Your browser doesn't support the navigator.preferences API",
  );
}

Kết quả

Thông số kỹ thuật

Thông số kỹ thuật
Media Queries Level 5
# preferences-attribute

Tương thích trình duyệt

api.Navigator.preferences

api.PreferenceManager

api.PreferenceObject