使用JavaScript

时间:2018-02-20 14:08:49

标签: javascript html5

我尝试使用以下代码禁用鼠标选择

var unFocus = function () {
  if (document.selection) {
    document.selection.empty()
  } else {
    window.getSelection().removeAllRanges()
  }
}

document.getElementById("v_6").onmousemove = function () {
    unFocus()
}
document.getElementById("v_6").onmousedown = function () {
    unFocus()
}

我的主要问题是我希望获得onmousedown&的代码。 onmouse同时移动。所以现在如果我移动鼠标而没有选择带有onmousedown它会移除光标,但我不希望这种情况发生。我想知道如果两个事件同时发生,那么它执行该函数。 任何帮助都将非常感激

1 个答案:

答案 0 :(得分:2)

两个答案:

1。如果你真的想在主要("左边")按钮关闭的情况下移动鼠标时调用unFocus,那么你可以只使用mousemove处理程序,{{1}处理程序是必需的,因为事件对象具有mousedown值,其具有按钮向下的位标志; more on MDN

buttons

2。但是,如果您只是不允许用户选择,并且它不必使用JavaScript,只需在CSS中使用user-select: none元素:

document.getElementById("v_6").onmousemove = function () {
    if (e.buttons & 1 === 1) { // true when the primary button is down
        unFocus()
    }
};

示例:



/* I've used #v_6 to match your example, but obviously it can be any selector */
#v_6 {
   user-select: none;
   -moz-user-select: none;
   -webkit-user-select: none;
   -ms-user-select: none;
}

.no-select {
   user-select: none;
   -moz-user-select: none;
   -webkit-user-select: none;
   -ms-user-select: none;
}