gpt4 book ai didi

javascript - 在 javascript 或 jquery 中检测鼠标的当前状态,即向下或向上

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:13 25 4
gpt4 key购买 nike

我正在构建一个 Web 应用程序,它涉及从网页内和其他应用程序(例如 word 和 pdf 文档)拖放大量文本。如果按下(单击)或向上(释放),我需要获取鼠标的当前状态。目前,如果我在网页中拖动文本,我可以获取鼠标的当前状态,但如果鼠标来自另一个应用程序说出的单词并拖动一些文本,则无法获取鼠标状态。非常感谢任何获取鼠标按下或向上状态的指针。

最佳答案

我理解的问题是,如果在窗口外按下鼠标左键(用于拖动操作),您需要确定是否按下鼠标左键。

有很多问题:

  • 在拖动操作期间没有触发 mousemove 事件
  • 当前按钮状态的数据因浏览器而异

我想出了这个解决方案:

/**
* keeps track of the current active mouse button.
* @param notifier {Function} called when the active button is updated.
* @param oneCallPerStateChange {Boolean} (defaults to false) if true the notifier will be called only when the active button changes.
*/
function initActiveButtonWatcher(notifier, oneCallPerStateChange) {

// create variable to store button states.
var _activeButton = -1, activeButton = 0

// function to set the current active button.
function updateMouseState(e) {

// update active button.
activeButton = typeof e.buttons === "number" ? e.buttons : e.which

// notify if the active button is different.
if ( oneCallPerStateChange? (_activeButton !== activeButton && typeof notifier === "function") : (typeof notifier === "function")) {
notifier(activeButton)
}

// store the last state in order to be able to tell if the state has changed.
_activeButton = activeButton
}

// function to get the current active button.
function getButtonState() { return activeButton }

// update the button state when the mouse is moved
// or an item is dragged into the window.
window.addEventListener("mousemove", updateMouseState, false)
window.addEventListener("dragover", function() { updateMouseState({which: 1}) }, false)
window.addEventListener("dragleave", function() { updateMouseState({which: 0}) }, false)

// expose the getter on the global object.
window.getButtonState = getButtonState
}

上述解决方案绑定(bind)到 mousemove 事件和 dragover 事件。Chrome 在 dragover 事件中获得了一个具有正确按钮值的有效事件对象,但我发现 FireFox 没有。我觉得鼠标左键的状态在拖拽操作中很明显,应该是按下,对吧?不单击和移动就不能拖动。所以我只是在 dragover 上将状态设置为 1(左下)。同样,在 dragleave 上,该值设置为零。

您将执行所有正常的 dragover、dragstart、end、drop 等处理以防止默认浏览器操作,并且 window.getButtonState() 返回的值应始终是当前事件鼠标按钮的值。

下面是一些将页面中第一个 h1 标签的值设置为当前按下的按钮的用法示例:

;(function() {

var active = document.getElementsByTagName("h1")[0]

function translate(n) {
switch (n) {

case 0:
return "none"
break;
case 1:
return "left"
break;
case 2: case 4: // Firefox calls it 4, the values differ between browsers I find.
return "middle"
break;
case 3:
return "right"
}
}

initActiveButtonWatcher(
function(currentActive) {
active.innerHTML = "Active button: " + translate(currentActive)
}
)

})()

您必须对跨浏览器进行一些调整以处理不同的值(FF 报告中间按钮为 4,等等)但您应该能够使用此方法相当好地获得当前按钮。

尝试一下:http://jsfiddle.net/6BUA4/

关于javascript - 在 javascript 或 jquery 中检测鼠标的当前状态,即向下或向上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10103298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com