在 div 上阻止 select 允许 select 在 div 周围

Blocking select on a div allows select around a div

我有一份 HTML 文件。它需要在尽可能多的浏览器上工作。

我阻止 select 访问某些项目,特别是 div 中包含的项目。这行得通,它没有得到 selected。但是,当您单击 inside that div 然后将指针拖动到 outside 时,selecting 继续发生在div,还有蓝色的select离子盒等

我希望那不会发生。

我需要它以便:

请参阅下面的示例 - 当您在框内单击然后移动鼠标时,框内的内容不会 selected(在我的生产代码中,框甚至不会突出显示)但两者之间的所有内容他们确实如此。

(请注意,可能有一个或多个 div——在下面的示例中我有 3 个)。

我已经尝试了很多东西 - 取消各种元素的 mousedown,取消各种元素的 selectstart 和 body(包括捕获阶段而不是气泡)等等等等。它仍然发生。

我特别困惑的是,取消 body 上的 selectstart 不起作用(至少在 Chrome 中,可能在其他情况下)。我已经给出了我为此使用的示例代码(如果我们在框中开始,则不包括捕获逻辑)。

我相信这是可能的 - 如果您打开 youtube 并尝试 click/hold 在视频的位置滑块上,然后 move/drag 在视频框外,什么也得不到 select编辑

我可能遗漏了一些明显的东西 - 我在这里陷入困境 - 但有人可以帮忙吗?

PS 是的,我知道代码不是很好,它是我完整代码的 cut-down 版本。

<!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;