简体   繁体   English

如何使用JavaScript设置CSS3 :: selection

[英]How to set CSS3 ::selection using Javascript

Does anyone have an idea how to execute this CSS rule dynamically using Javascript and then disable it (particularly to suppress annoying selection in Chrome during certain mouse gestures): 有谁知道如何使用Javascript动态执行此CSS规则然后禁用它(特别是在某些鼠标手势期间抑制Chrome中令人讨厌的选择):

::selection{
    background:transparent;
}

Eg: document.body.style['::selection']['background']="transparent"; 例如: document.body.style['::selection']['background']="transparent"; , but of course it doesn't work. ,但是当然不起作用。

Some ways I can think of: 我可以想到的一些方法:

JS JS

document.addEventListener("selectstart", function(){return false;});

CSS CSS

pointer-events: none;

I tried this workaround, it works: 我尝试了这种解决方法,它的工作原理是:

var styleElem=document.createElement('style'); 
styleElem.innerHTML='::selection{ background:transparent; }';

// enable in some cases
document.head.appendChild(styleElem);

// disable when not needed
window.getSelection().removeAllRanges();
document.head.removeChild(styleElem);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM