有div
我在其中使用onclick
函數重定向其他頁面。Javascript和ctrl鍵衝突
但是,當我使用Ctrl鍵和鼠標時,鏈接在下一個選項卡以及相同的選項卡中打開。理想情況下,它應該只在新選項卡中打開。
代碼如下:
<div onclick="window.location='some page url'">
有div
我在其中使用onclick
函數重定向其他頁面。Javascript和ctrl鍵衝突
但是,當我使用Ctrl鍵和鼠標時,鏈接在下一個選項卡以及相同的選項卡中打開。理想情況下,它應該只在新選項卡中打開。
代碼如下:
<div onclick="window.location='some page url'">
只是這樣做:
<a href="some page url">
<div></div>
</a>
所以,當你點擊它在同一個標籤中打開當你按下ctrl鍵時,它會在新選項卡中打開。
編輯:所以現在試試這個:
<div onclick="doRedirect()"></div>
<script>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function doRedirect()
{
if(cntrlIsPressed)
{
window.open('some url','_blank');
}
else{
window.location('some url');
}
}
</script>
您還可以在參數中指定的網址。
<div onclick="window.open(
'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
'_blank' // <- This is what makes it open in a new window.
);">
Click to open in tab
</div>
這裏是工作example
感謝您的回答,但它阻止了默認的點擊功能。當用鼠標點擊它時,它應該在同一個標籤中的頁面上重定向。當用Ctrl鍵按下鼠標時,它應該只在新選項卡中打開。 –
你爲什麼用onclck做這個?無論如何,這是默認的瀏覽器行爲。 –
@DaveNewton是的,你是對的。但是,當我使用簡單的'window.location =「一些url」'同樣的事情發生。 –