我有一个 HTML 文档。它需要在尽可能多的浏览器上工作。
我阻止选择某些元素,特别是那些包含在 div 中的元素。那行得通,它没有被选中。但是,当您单击该 div 的内部,然后将指针拖动到外部时,选择继续发生在 div 的外部,您会看到蓝色的选择框等。
我希望那不会发生。
我需要它以便:
如果您在框外单击(从框外开始),您可以正常选择/拖动,包括框周围(但不在框内)。坦率地说,我在这里的行为很好。
如果在框内单击,则无法选择或拖动,即使在框外也是如此。
请参见下面的示例 - 当您在框内单击然后移动鼠标时,框的内容未被选中(在我的生产代码中,框甚至没有突出显示)但它们之间的所有内容都被选中。
(请注意,可能有一个或多个 div - 在下面的示例中我有 3 个)。
我已经尝试了很多东西 - 取消各种元素的 mousedown,取消各种元素和主体的 selectstart(包括在捕获阶段而不是气泡)等等。它仍然发生。
我特别困惑的是,取消 body 上的 selectstart 不起作用(至少在 Chrome 中,可能在其他浏览器中)。我已经给出了我为此使用的示例代码(如果我们在框中开始,则不包括捕获逻辑)。
我相信这是可能的 - 如果您打开 youtube 并尝试单击/按住视频的位置 slider ,然后移动/拖动到视频框外,则不会选择任何内容。
我可能遗漏了一些明显的东西 - 我在这里陷入困境 - 但任何人都可以帮忙吗?
PS 是的,我知道代码不是很好,它是我完整代码的精简版。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
.Box
{
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-webkit-touch-callout: none;
-webkit-user-drag: none;
background-color: white;
border-color: rgb(204, 204, 204);
border-style: solid;
border-width: 4px;
}
</style>
</head>
<body>
<div id="Box1" class="Box" unselectable="on" style="width:400px; height:100px;">Box1</div>
<br />
<div id="Box2" class="Box" unselectable="on" style="width:400px; height:100px;">Box2</div>
<br />
<div id="Box3" class="Box" unselectable="on" style="width:400px; height:100px;">Box3</div>
<br />
<script>
this.blockSelect = function()
{
// for ie < 10
var box1 = document.getElementById('Box1');
var box2 = document.getElementById('Box2');
var box3 = document.getElementById('Box3');
box1.onselectstart = function() {
return false;
};
box2.onselectstart = function() {
return false;
};
box3.onselectstart = function() {
return false;
};
}
blockSelect();
</script>
</body>
</html>
捕获取消:
this.cancelBubble = function(e)
{ // called from within an event, and passes that as e
var evt = e ? e:window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
this.eventDocOnSelectStart = function(e)
{
if (true)
{
cancelBubble(e);
return false;
}
};
document.body.addEventListener("selectstart", this.eventDocOnSelectStart, true);
最佳答案
当鼠标悬停在框上时,在 body
上添加 user-select: none;
。
关于javascript - 在 div 上阻止选择允许在 div 周围选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33911521/