如何在html或JS中禁用突出显示?

Joh*_*mac 23 html javascript css highlight

我需要在我的网络应用程序上禁用所选文本的突出显示.我有充分的理由这样做,并知道这通常是一个坏主意.但无论如何我还是需要这样做.如果我需要使用CSS或JS来做这件事并不重要.我主要想要的是去除突出显示元素的蓝色.

Erv*_*Erv 21

你可以使用css伪类选择器(:: selection和:: - moz-selection for firefox).例

::-moz-selection {
    background-color: transparent;
    color: #000;
}

::selection {
    background-color: transparent;
    color: #000;
}

.myclass::-moz-selection,
.myclass::selection { ... }
Run Code Online (Sandbox Code Playgroud)

  • 它不会停止选择(如果你需要它至少使用javascript - >我使用jquery:window.onload = function(){document.onselectstart = function(){return false;} //即document.onmousedown = function() {return false;} // mozilla} U可能需要额外的脚本来取消Windows CTRL + A中的键盘快捷键.但是再次确实没有可靠的方法来阻止计算机"专家"复制他们在计算机上看到的内容. (6认同)
  • 你能用这个吗:http://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting (2认同)

mys*_*dat 8

CSS3解决方案:

user-select: none;
-moz-user-select: none;
Run Code Online (Sandbox Code Playgroud)

用户选择还有一个webkit前缀,但它使一些表单字段无法集中(可能是一个临时错误),因此您可以使用以下伪类来代替webkit:

element::selection
Run Code Online (Sandbox Code Playgroud)


Rex*_*x M 5

我相信你的意思是选择文字(例如,将鼠标拖过来突出显示).如果是这样,这将取消IE和Mozilla中的选择操作:

window.onload = function() {
  if(document.all) {
      document.onselectstart = handleSelectAttempt;
  }
  document.onmousedown = handleSelectAttempt;
}

function handleSelectAttempt(e) {
    var sender = e && e.target || window.event.srcElement;
    if(isInForm(sender)) {
        if (window.event) {
            event.returnValue = false;
        }
        return false;
    }
    if (window.event) {
        event.returnValue = true;
    }
    return true;
}

function isInForm = function(element) {
    while (element.parentNode) {
        if (element.nodeName.ToUpperCase() == 'INPUT'
            || element.nodeName.ToUpperCase() == 'TEXTAREA') {
            return true;
        }
        if (!searchFor.parentNode) {
            return false;
        }
        searchFor = searchFor.parentNode;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)