簡體   English   中英

使用javascript或jquery模擬ctrl +單擊(打開沒有焦點的新選項卡)

[英]simulate ctrl + click with javascript or jquery (to open a new tab without focus)

我正在玩jquery事件對象,但我被困在地獄

我閱讀了API https://api.jquery.com/category/events/event-object/但它在這里並沒有真正起作用,我甚至不確定這是一個很好的領導

你有什么建議(問題是要完全按住ctrl +點擊一個鏈接)。 我看到了一些關於它的帖子,但似乎在最近的瀏覽器上沒有任何效果

非常簡單的例子:

<span id="toto">toto</span>
<a href="https://google.fr" id="inANewTab"></a>

// The goal is when I click on #toto, I would like #inANewTab trigger 
// in a new tab without focus. To do that I was thinking
// about replicate a ctrl+click event

$('#toto').click(function(){
  ???
})

編輯:

jQuery中的Event對象有一個ctrlKey參數,你可以在點擊時將其指定為true。

var e = jQuery.Event("click");
e.ctrlKey = true;
$('#id').trigger(e);

參考: jquery觸發器ctrl +單擊

這是一個非jQuery版本來模擬鍵盤事件。 這適用於Chrome(基於WebKit)和Firefox(基於Gecko):

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


keyboardEvent[initMethod](
                   "keydown", // event type : keydown, keyup, keypress
                    true, // bubbles
                    true, // cancelable
                    window, // viewArg: should be window
                    false, // ctrlKeyArg
                    false, // altKeyArg
                    false, // shiftKeyArg
                    false, // metaKeyArg
                    40, // keyCodeArg : unsigned long the virtual key code, else 0
                    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);

或者使用jQuery,您可以通過jQuery的event對象進行模擬:

jQuery.event.trigger({
  type:  'keypress',
  which: character.charCodeAt(0)
});

在純JavaScript中,您可以使用MouseEvent

document.getElementById("todo").dispatchEvent(new MouseEvent("click", {ctrlKey: true}));

要以編程方式打開新選項卡,您可以執行以下操作:

const a = document.createElement("a");
a.setAttribute("href", "https://www.google.com/");
a.dispatchEvent(new MouseEvent("click", {ctrlKey: true}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM