2012-05-19 65 views
1

使用此操作我想更改文檔的默認選擇行爲。我通過getElmentsByTagName爲文檔主體執行此操作。但是代碼實際上並沒有達到預期效果,這是爲了防止用戶點擊以選擇文檔中的文本。更改整個文檔或窗口的默認選擇行爲

<script> 
    $(document).ready (function() { 
     document.getElementsByTagName("body").addEventListener('mousedown', function(e) { e.preventDefault(); }, false); 
    }); 
</script> 

這在我的網站上的其他地方工作,以防止選擇特定的頁面元素。我如何爲整個文檔做這件事?

+0

你可以防止選擇純粹使用CSS:http://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting – RoccoC5

回答

0

發現我也可以用這個CSS做到這一點。

<style> 
*:not(input) { 
-webkit-touch-callout: none; 
-webkit-user-select: none; 
-khtml-user-select: none; 
-moz-user-select: none; 
-ms-user-select: none; 
user-select: none;  
} 
</style> 
0

您的函數中存在拼寫錯誤。當您使用getElementsByTagName選擇元素時,即使頁面上只有一個元素,實際上也會收到集合。因此,使用[0]來指示要集合中返回的第一個body元素:

document.getElementsByTagName("body")[0]. 
     addEventListener('mousedown', 
      function(e) { 
       e.preventDefault(); 
      }, false); 

這當然會阻止選定的文本,從而使解決您的問題。

UPDATE:

我剛纔意識到你並不需要禁用點擊錨標記,但在這裏我要離開這個對於要禁用這些點擊,以及人。

但是,爲了防止鏈接被點擊,就必須使用另一種方法:

// bind click event to parent elements of anchor tags, 
// or it won't work properly 
$('a').parent().each(function() { 
    $(this).attr("href","#"); 
    $(this).unbind(); 
    $(this).click(function() { 
     event.preventDefault(); 
     return false; 
    }); 
}); 
0
$(document).ready (function() { 
    $(document).on('mousedown', function(e) { 
     e.preventDefault(); 
    }); 
});​ 

Another answer on SO.