2016-03-04 49 views
1

我有以下腳本,它給予用戶特定元素的網址(當前URL加上元素的#id作爲錨點)。我的腳本執行當用戶點擊元素,OK,那是不是我想要的,我想這一點:如何確定ctrl是否在點擊之前按下?

如果CTRL被按下,用戶點擊該元素,然後在下面運行腳本上。然後將該URL複製到用戶系統的剪貼板中。

我該怎麼做?

// I need to write a condition here to check whether ctrl is pressed? 
 

 
$("div").on("click", function(){ 
 
    var url    = window.location.href; 
 
    var anchor  = $(this).attr("id"); 
 
    var url_of_elm = url + "#" + anchor; 
 
    
 
    console.log(url_of_elm); 
 
    
 
    // I need to copy url_of_elm in the clipboard of the user 
 

 
    alert("URL of element is copied"); 
 

 
});
div{ 
 
    border: 1px solid gray; 
 
    margin: 5px; 
 
    padding: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id = "1"> 
 
    <h2>title1</h2> 
 
    <p>content1</p> 
 
    <span>something else</span> 
 
</div> 
 

 
<div id = "2"> 
 
    <h2>title2</h2> 
 
    <p>content2 <span>the rest of content2</span></p> 
 
    <span>something else</span> 
 
</div> 
 

 
<div id = "3"> 
 
    <h2>title3</h2> 
 
    <p>content3 <a>a link in the content3</a></p> 
 
    <span>something else</span> 
 
</div>

回答

4

變化

$("div").on("click", function(){ 

$("div").on("click", function(event){ 

,然後內部檢查

if(event.ctrlKey){ 
    \\Ctrl key is pressed! 

編輯:JSFiddle

+0

他們這樣做,我會用小提琴 –

+0

@RoryMcCrossan更新的答案其實他們這樣做。另外shiftKey道具 – charlietfl

+0

還AltKey .. –

3

您可以通過鉤住的keydown和keyup事件偵聽器來設置一個標誌指示是否被按下的CTRL關鍵文檔實現這一目標。然後你可以在你的點擊處理程序中檢查這個標誌。試試這個:

ctrlKeyDown = false; 
 

 
$(document).on({ 
 
    keydown: function(e) { 
 
     ctrlKeyDown = e.ctrlKey; 
 
    }, 
 
    keyup: function() { 
 
     ctrlKeyDown = false; 
 
    } 
 
}); 
 

 
$("div").on("click", function(){ 
 
    if (ctrlKeyDown) { 
 
     var url = window.location.href; 
 
     var anchor = $(this).attr("id"); 
 
     var url_of_elm = url + "#" + anchor; 
 
     alert(url_of_elm); 
 
    } 
 
});
div{ 
 
    border: 1px solid gray; 
 
    margin: 5px; 
 
    padding: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id = "1"> 
 
    <h2>title1</h2> 
 
    <p>content1</p> 
 
    <span>something else</span> 
 
</div> 
 

 
<div id = "2"> 
 
    <h2>title2</h2> 
 
    <p>content2 <span>the rest of content2</span></p> 
 
    <span>something else</span> 
 
</div> 
 

 
<div id = "3"> 
 
    <h2>title3</h2> 
 
    <p>content3 <a>a link in the content3</a></p> 
 
    <span>something else</span> 
 
</div>

+2

有沒有必要使用另一個變量來做到這一點.. –

+0

謝謝..它的工作原理,+1。請您在用戶系統的童年時間複製該URL? – stack

+0

@LucaDeNardi使它跨瀏覽器工作。 –

相關問題