紀錄工作經驗、相關知識,解決技術相關問題。

CSS, HTML, 工作雜談

CSS 禁止選取文字:去除 HTML 點擊反白藍色背景 (user-select: none)

CSS 禁止選取文字:去除 HTML 點擊反白藍色背景 (user-select: none) 特色圖片

在製作網頁互動元件(例如輪播圖切換箭頭、計數器加減按鈕、自訂頁籤或手機端導覽列)時,使用者若連續快速點擊兩下,常會不小心選取到按鈕上的文字,使得內文背景出現一塊反藍色。

若要透過 css 禁止選取 HTML 文字、去除點擊選取時出現的藍色背景,只需要加上 user-select: none 即可。


1. CSS 禁止選取文字語法(user-select: none)

將以下 Class 套用在按鈕、輪播控制器或不想被反白複製的區塊上,即可跨瀏覽器禁止文字選取:

.no-select {
  -webkit-user-select: none; /* Safari、iOS Safari */
  -moz-user-select: none;    /* 舊版 Firefox */
  -ms-user-select: none;     /* 舊版 IE10+ / Edge */
  user-select: none;         /* 標準語法(Chrome、現代瀏覽器) */
}

提示:如果是手機版點擊超連結或按鈕「瞬間閃過」的半透明藍色方框(並非文字被反白選取),請搭配 -webkit-tap-highlight-color: transparent; 去除,詳細說明可參考 css 移除超連結顏色 藍色外框 / CSS remove hyperlink blue box。


2. 進階實用技巧:點擊一下自動全選文字(user-select: all)

除了禁止選取之外,user-select 還有一個在開發「優惠碼、邀請碼、API 金鑰或短網址複製框」時非常好用的屬性值 user-select: all。設定後,只要使用者用滑鼠左鍵點一下該區塊,瀏覽器就會自動幫他把整段文字全選起來:

.select-all-on-click {
  user-select: all;
  cursor: pointer;
}

3. 自訂文字選取時的反白背景顏色(::selection)

如果內文允許使用者正常選取複製,但希望把瀏覽器預設刺眼的深藍色反白背景改成符合網站品牌的配色,可以使用 ::selection 偽元素:

/* 自訂全站文字被滑鼠反白選取時的背景色與文字色 */
::selection {
  background-color: #fef08a; /* 柔和黃底 */
  color: #1e293b;            /* 深灰字體 */
}

user-select 常用屬性值比較表

屬性寫法選取行為說明常見應用場景
user-select: none完全禁止滑鼠拖曳或連點選取文字按鈕、下拉選單標題、輪播左右箭頭、遊戲介面
user-select: all滑鼠點擊一下即自動選取整個元素內的所有文字優惠碼、訂單編號、程式碼片段、分享網址框
user-select: text允許選取文字(可在父層 none 時替特定子元素恢復選取)被包裹在互動卡片內但需要讓用戶複製的資訊
user-select: auto瀏覽器預設行為一般文章段落

參考資料

6 留言

  1. I am an investor of gate io, I have consulted a lot of information, I hope to upgrade my investment strategy with a new model. Your article creation ideas have given me a lot of inspiration, but I still have some doubts. I wonder if you can help me? Thanks.

  2. Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  3. Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  4. I have read your article carefully and I agree with you very much. So, do you allow me to do this? I want to share your article link to my website: Cryptocurrency Prices

  5. Do you mind if I quote a couple of your articles as long asI provide credit and sources back to your website?My blog site is in the very same niche as yours and my users would certainly benefit from some of the information you present here.Please let me know if this okay with you. Thanks!

發佈留言