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

Cách Disable Text Selection với CSS

Tìm hiểu cách vô hiệu hóa text selection bằng CSS property user-select.

Mặc định, trình duyệt web cho phép select text trên bất kỳ website nào — miễn là nó là element text thật chứ không phải ảnh có text trên đó.

Bạn có thể select text bằng chuột, hoặc bàn phím, ví dụ cmd + a (Mac), hoặc ctrl + a (Windows).

Nhưng nếu bạn không muốn cho phép text selection (với lý do gì đó)?

Bạn dùng CSS property user-select và cho giá trị none:

selector { user-select: none; }

Giả sử bạn muốn disable text selection trên mọi element có class .select-none:

.select-none { user-select: none; }

Rồi thêm class đó vào bất kỳ element nào bạn muốn disable text selection:

<p class="select-none">This text cannot be selected.</p>

Demo:

Element text này không thể select, thử xem!

Lưu ý: bạn cần dùng các browser prefixes sau cho property user-select để hoạt động trên mọi trình duyệt:

-webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;