Last active
August 29, 2015 14:10
-
-
Save foolyoghurt/cb79a171104f7bc21f57 to your computer and use it in GitHub Desktop.
Javascript Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>openNewBackgroundTab</title> | |
</head> | |
<body> | |
<a href="http://baidu.com">baidu.com</a> | |
</body> | |
<script charset="utf-8"> | |
function openNewBackgroundTab(e) { | |
e.preventDefault(); | |
// 创建一个新元素,否则在同一个元素上监听元素的 click 事件后,又触发一个新的 click 事件,造成死循环 | |
var a = document.createElement("a"); | |
a.href = this.href; | |
var evt = document.createEvent("MouseEvents"); | |
// No.10 -> ctrl key for Windows/Linux, No.13 -> command key for OS X | |
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null); | |
a.dispatchEvent(evt); | |
a = null; | |
} | |
document.querySelector("a").addEventListener("click", openNewBackgroundTab, false); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment