阻止在HTML中进行选择 [英] Prevent selection in HTML

查看:113
本文介绍了阻止在HTML中进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML页面上有一个div,每当我按下鼠标并移动它时,它就会显示不能删除光标,就像它选择了一些东西。有没有办法禁用选择?

I have a div on a HTML page and whenever I press the mouse and move it, it will show that "can't drop" cursor like it selects something. Is there a way to disable selection? I tried CSS user-select with none without success.

推荐答案

user-select 可以在大多数现代浏览器中使用:

The proprietary variations of user-select will work in most modern browsers:

*.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

对于IE< 10和Opera,您需要使用您希望取消选择的元素的不可选属性。您可以使用HTML中的属性来设置它:

For IE < 10 and Opera, you will need to use the unselectable attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:

<div id="foo" unselectable="on" class="unselectable">...</div>

遗憾的是,这个属性并没有被继承,这意味着你必须在每个开始标签中放置一个属性< div> 中的元素。如果这是一个问题,您可以使用JavaScript对元素的后代递归地执行此操作:

Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:

function makeUnselectable(node) {
    if (node.nodeType == 1) {
        node.setAttribute("unselectable", "on");
    }
    var child = node.firstChild;
    while (child) {
        makeUnselectable(child);
        child = child.nextSibling;
    }
}

makeUnselectable(document.getElementById("foo"));

这篇关于阻止在HTML中进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆