DIV CSS 佈局教程網

禁止選取文字的跨瀏覽器寫法(IE、Chrome、Firefox 通用)
編輯:JQuery特效代碼     

某些介面(拖曳排序的清單、可拖動的浮動視窗、模擬桌面圖示)一旦讓使用者把文字反白選起來,拖曳就會變成選字,操作體驗瞬間破功。要禁掉這個行為,得同時下藥在 CSS 與事件兩處。

一、用 jQuery 一次綁好

$(el).attr('unselectable', 'on')
      .css({
          '-moz-user-select': '-moz-none',
          '-moz-user-select': 'none',
          '-o-user-select': 'none',
          '-khtml-user-select': 'none',
          '-webkit-user-select': 'none',
          '-ms-user-select': 'none',
          'user-select': 'none'
      })
      .bind('selectstart', function () { return false; });

這段做了三件事:unselectable="on" 是 IE 的老寫法;一整排加上前綴的 user-select 對應各家的私有實作;selectstart 回傳 false 則是 IE 攔截選取開始的事件手段。

二、更推薦的做法:寫進 CSS class

把這些屬性塞在 inline style 裡維護性很差。實務上乾脆開一個 class,需要禁選區塊時掛上去就好。

.table {
    text-align: center;
    vertical-align: middle;
    height: 39px;
    overflow: hidden;

    -moz-user-select: -moz-none;
    -moz-user-select: none;
    -o-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;   /** 禁止選中文字 **/
}

注意 -moz-user-select 寫了兩次是刻意的:較舊的 Firefox 只吃 -moz-none,新版則認 none,兩行並存才能涵蓋整個版本區間。

三、別忽略的副作用

關掉選取之後,使用者也無法用 Ctrl+C 複製該區域的文字。因此這個技巧應該只套用於「純操作介面」元素(工具列、標籤頁、拖曳把手),絕對不要套在文章正文、表格資料、序號或任何使用者可能想複製的內容上——那會是實打實的可用性傷害,對有障礙的使用者尤其不友善。若只是為了防抄,CSS 攔截既不可靠也容易規避,不如把力氣花在真正的內容保護與法律手段上。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved