1

有了这个,我想更改文档的默认选择行为。我对文档正文使用getElmentsByTagName. 但是代码实际上并没有达到想要的效果,就是阻止用户点击选择文档中的文本。

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

这适用于我网站的其他地方,以防止在特定页面元素上进行选择。如何对整个文档执行此操作?

4

3 回答 3

0

您的函数中有错字。当您使用 getElementsByTagName 选择一个元素时,您实际上是在接收一个集合,即使页面上只有一个元素。因此,使用 [0] 表示您希望在集合中返回第一个正文元素:

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

这当然会阻止选择文本,从而解决您的问题。

更新:

我刚刚意识到您不需要禁用单击锚标记,但我会将其留给想要禁用这些单击的人。

但是,为了防止链接被点击,您必须使用另一种方法:

// 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;
    });
});
于 2012-05-19T19:04:27.973 回答
0
$(document).ready ( function () {
    $(document).on('mousedown', function(e) { 
        e.preventDefault(); 
    });
});​

关于SO的另一个答案。

于 2012-05-19T19:04:40.363 回答
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>
于 2012-05-19T19:16:02.037 回答