if (typeof(element.onselectstart) != "undefined") { // IE下禁止元素被選取 element.onselectstart = new Function("return false"); } else { // firefox下禁止元素被選取的變通辦法 element.onmousedown = new Function("return false"); element.onmouseup = new Function("return true"); }
IE下有onselectstart這個方法,通過設置這個方法可以禁止元素文本被選取。而firefox下沒有這個方法,但可以通過css或一種變通的辦法解決:
使用CSS:
div { -moz-user-select:none; -webkit-user-select:none; user-select:none; }
另外一種方法是:
ie:document.selection.empty()
ff:window.getSelection().removeAllRanges()
兼容的寫法:
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
這種方法不但不影響拖放對象的選擇效果,還能對整個文檔進行清除.