我使用javascript来禁用我的网站上的文字选择。
代码是:
<script type="text/JavaScript">
function disableselect(e) {
return false
}
function reEnable() {
return true
}
document.onselectstart = new Function ("return false")
if (window.sidebar) {
document.onmousedown = disableselect
document.onclick = reEnable
}
</script>
可以找到类似的脚本here
在我的本地主机上:所有浏览器(Firefox,Chrome,IE和Safari)运行良好。
在我的实时网站上:除了Firefox之外一切正常。
我的问题是:
有没有人建议为什么Firefox对于实时网站和本地主机的行为不同。注意:Javascript已启用。
也许我的剧本太简单了,所以我已经尝试了following完全相同的结果
答案 0 :(得分:172)
只需使用此css方法:
body{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
您可以在此处找到相同的答案:How to disable text selection highlighting using CSS?
答案 1 :(得分:18)
我正在编写滑块ui控件以提供拖动功能,这是我阻止用户拖动时选择内容的方法:
function disableSelect(event) {
event.preventDefault();
}
function startDrag(event) {
window.addEventListener('mouseup', onDragEnd);
window.addEventListener('selectstart', disableSelect);
// ... my other code
}
function onDragEnd() {
window.removeEventListener('mouseup', onDragEnd);
window.removeEventListener('selectstart', disableSelect);
// ... my other code
}
在你的dom上绑定startDrag
:
<button onmousedown="startDrag">...</button>
如果要在所有元素上静态禁用文本选择,请在加载元素时执行代码:
window.addEventListener('selectstart', function(e){ e.preventDefault(); });
答案 2 :(得分:11)
对于JavaScript使用此功能:
function disableselect(e) {return false}
document.onselectstart = new Function (return false)
document.onmousedown = disableselect
启用选择使用此:
function reEnable() {return true}
并在任何地方使用此功能:
document.onclick = reEnable
答案 3 :(得分:4)
如果您有这样的html页面:
<body onbeforecopy = "return false" ondragstart = "return false" onselectstart = "return false" oncontextmenu = "return false" onselect = "document.selection.empty()" oncopy = "document.selection.empty()">
有一种简单的方法可以禁用所有事件:
document.write(document.body.innerHTML)
你获得了html内容并丢失了其他内容。
答案 4 :(得分:0)
简单复制此文本并放在Public Class DocumentReadyListender
Implements IDocumentReadyListener
之前的
</body>
答案 5 :(得分:0)
一个人可能还会使用:
onselectstart = (e) => {e.preventDefault()}
示例:
onselectstart = (e) => {
e.preventDefault()
console.log("nope!")
}
Select me!
另一种方法是通过测试CSS支持,并禁用用户选择:
let FF
if (CSS.supports("( -moz-user-select: none )")){FF = 1} else {FF = 0}
(FF===1) ? document.body.style.MozUserSelect="none" : document.body.style.userSelect="none"