Javascript 模拟移位鼠标单击
有没有一种方法可以模拟Shift+单击 这段代码运行得很好,但目前没有转换:Javascript 模拟移位鼠标单击,javascript,jquery,Javascript,Jquery,有没有一种方法可以模拟Shift+单击 这段代码运行得很好,但目前没有转换: //--- 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. trigge
//--- 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);
}
更新:如果你想触发shift+点击事件,你可以看到这篇文章 如果要模拟按住shift键并单击,则应使用initMouseEvent而不是initEvent。检查下面的小提琴 参考资料: 如果您想知道是否按下了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>
document.getElementById(“测试”).addEventListener(“单击”),函数(事件){
if(事件移位键){
console.log('shift pressed');
}否则{
console.log(“未按下shift”);
}
},假);
参考:
JSFiddle:
注意:initEvent和initMouseEvent都不推荐使用,因此为了安全起见,您可能希望使用另一个堆栈溢出答案()中提供的jQuery解决方案。您提到的jQuery方法的问题是,它在某些情况下不起作用。有时需要复制整个序列:mouseover、mousedown、mouseup、click。