有没有办法以某种方式模拟Shift + Click?
此代码运行良好,但目前没有转移:
//--- Get the first link that has "stackoverflow" in its URL.
var targetNode = document.querySelector ("a[href*='stackoverflow']");
if (targetNode) {
//--- Simulate a natural mouse-click sequence.
triggerMouseEvent (targetNode, "mouseover");
triggerMouseEvent (targetNode, "mousedown");
triggerMouseEvent (targetNode, "mouseup");
triggerMouseEvent (targetNode, "click");
}
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
答案 0 :(得分:6)
更新:如果您想触发shift + click事件,可以看到此帖子
<强> shift mouse click trigger 强>
如果你想模拟shift + click,那么你应该使用initMouseEvent而不是initEvent。检查以下小提琴。
https://jsfiddle.net/zqdftehw/2/
参考文献:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent http://marcgrabanski.com/simulating-mouse-click-events-in-javascript/
如果您想知道是否按下了shift键,则以下内容将起作用,
<div id="test"></div>
<script>
document.getElementById("test").addEventListener("click", function( event ) {
if (event.shiftKey) {
console.log('shift pressed');
} else {
console.log('shift not pressed');
}
}, false);
</script>
参考:https://developer.mozilla.org/en/docs/Web/Events/click
JSFiddle:https://jsfiddle.net/zqdftehw/1/
注意:不推荐使用initEvent和initMouseEvent,因此您可能希望使用另一个堆栈溢出答案(link mentioned above)中提供的jQuery解决方案,以便更安全。