单击之前如何确定按下ctrl?

时间:2016-03-04 12:07:20

标签: javascript jquery html css

我有以下脚本,它为用户提供特定元素的URL(当前URL加上元素的#id作为锚点)。我的脚本在用户点击元素时执行,好吧,这不是我想要的,我想要这个:

如果按 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>

2 个答案:

答案 0 :(得分:4)

更改

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

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

然后在里面检查

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

编辑: JSFiddle

答案 1 :(得分: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>