最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Simulate shift-mouseclick - Stack Overflow

programmeradmin0浏览0评论

Is there a way to somehow simulate Shift+Click?

This code works quite well, but currently, without 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.
    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);
}

Is there a way to somehow simulate Shift+Click?

This code works quite well, but currently, without 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.
    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);
}
Share Improve this question asked Feb 4, 2016 at 1:03 user90726user90726 9751 gold badge10 silver badges33 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

Update: If you want to trigger shift+click event, you can see this post

shift mouse click trigger

If you want to simulate shift+click, then you should use initMouseEvent instead of initEvent. Check the following fiddle.

https://jsfiddle/zqdftehw/2/

References:

https://developer.mozilla/en-US/docs/Web/API/MouseEvent/initMouseEvent http://marcgrabanski./simulating-mouse-click-events-in-javascript/

If you want to know whether shift key is pressed or not, then the following will work,

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

Reference: https://developer.mozilla/en/docs/Web/Events/click

JSFiddle: https://jsfiddle/zqdftehw/1/

Note: Both initEvent and initMouseEvent are deprecated, so you might want to use jQuery solution provided in the other stack overflow answer (link mentioned above) to be on safer side.

发布评论

评论列表(0)

  1. 暂无评论