我正在做一个HTML/CSS/jQuery图库,有几个页面。

我确实有一个“下一步”按钮,这是一个简单的链接与jQuery点击监听器。

问题是,如果用户多次单击按钮,则选择按钮的文本,然后选择整行文本。在我的黑暗设计中,这真的很丑陋和荒谬。

我的问题是:你能在HTML上禁用文本选择吗? 如果不是,我会非常想念flash和它在文本字段上的高级配置……


我不确定你是否可以关闭它,但你可以改变它的颜色:)

myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
    background:#000;
    color:#fff;
}

然后将颜色与你的“黑色”设计相匹配,看看会发生什么:)

<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>

你可以使用JavaScript来做你想做的事情:

if (document.addEventListener !== undefined) {
    // Not IE
    document.addEventListener('click', checkSelection, false);
} else {
    // IE
    document.attachEvent('onclick', checkSelection);
}

function checkSelection() {
    var sel = {};
    if (window.getSelection) {
        // Mozilla
        sel = window.getSelection();
    } else if (document.selection) {
        // IE
        sel = document.selection.createRange();
    }

    // Mozilla
    if (sel.rangeCount) {
        sel.removeAllRanges();
        return;
    }

    // IE
    if (sel.text > '') {
        document.selection.empty();
        return;
    }
}

肥皂盒: 您真的不应该以这种方式破坏客户端的用户代理。如果客户端希望选择文档上的内容,那么他们应该能够选择文档上的内容。如果您不喜欢突出显示的颜色,也没关系,因为您不是查看文档的人。

为了实现跨浏览器兼容性,可以试试下面的CSS代码。

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

2017年1月更新:

根据Can I use,除了ie9和更早的版本,目前所有浏览器都支持用户选择(但遗憾的是仍然需要一个供应商前缀)。


所有正确的CSS变体是:

.noselect { -webkit-touch-callout:没有;/* iOS Safari */ -webkit-user-select:没有;/* Safari */ -khtml-user-select:没有;/* Konqueror HTML */ -moz-user-select:没有;/* Firefox */ -ms-user-select:没有;/* Internet Explorer/Edge */ 用户选择:没有;/*当前无前缀版本 Chrome和Opera */支持 } < p > 可选择的文本。 < / p > < p class = " noselect " > 用来控制文本。 < / p >


注意,这是一个非标准特性(即不属于任何规范的一部分)。它不能保证在任何地方都能工作,而且不同浏览器的实现可能存在差异,将来浏览器可能会放弃对它的支持。


更多信息可以在Mozilla开发者网络文档中找到。