Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีปิด Text Selection ด้วย CSS

เรียนรู้ปิด text selection ด้วย CSS property user-select

Default เบราว์เซอร์อนุญาต select text บนเว็บไซต์ — ตราบใดที่เป็น real text element ไม่ใช่รูปภาพที่มีข้อความ

Select text ได้ด้วยเมาส์ หรือ keyboard เช่น cmd + a (Mac), ctrl + a (Windows)

แต่ไม่อยากให้ select text (เหตุผลไหนก็ตาม)?

ใช้ CSS property user-select ค่า none:

selector { user-select: "none"; }

เช่น อยากปิด text selection ทุก element ที่มี class .select-none:

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

เพิ่ม class ให้ element ที่อยากปิด selection:

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

Demo:

This text element cannot be selected, try yourself!

หมายเหตุ: ต้องใช้ browser prefixes สำหรับ user-select ให้ทำงานทุกเบราว์เซอร์:

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