【问题标题】:Simulate keypress in Javascript [duplicate]在Javascript中模拟按键[重复]
【发布时间】:2012-08-20 09:55:54
【问题描述】:

可能重复:
Can I do SendKeys in Javascript?

你好,有没有办法在javascript中做以下事情:

我希望用户点击网页上的一个链接,当点击该链接时,这相当于他们按 CONTROL + D,除非实际上没有按任何键。

谢谢

【问题讨论】:

  • 这正是它不起作用的原因。用户做一件事,而你在系统级别上做另一件事永远不会奏效。
  • 谢谢...现在我明白了

标签: javascript keypress simulate


【解决方案1】:

如果你使用 jQuery,你也许可以做这样的事情。

$("#linkId").click(function(event) {
    event.preventDefault(); // Stop the link click from doing anything.
    var ev = jQuery.Event("keypress"); // Build an event to simulate keypress.
    ev.which = 68; // Keycode for 'd' is 68
    ev.ctrlKey = true; // Control key is down.
    $(this).trigger(ev); // Fire!
});

【讨论】:

  • 只模拟为事件而不模拟为用户操作
【解决方案2】:

您只能在 jQuery 中模拟并将其作为事件进行跟踪,但您不能像用户按下这些按键一样进行操作。

这是一个无法用javascript 覆盖的安全问题。

【讨论】:

  • Mihai exists vreo posibilitate sa`ti pun o intrebare in privat ori undeva anume? ... e mai usor sa explic in romaneste...ms anticipat
  • Dar, ar fi pe chat
  • nu am acces, trebuie sa am reputatie minim "20" ... ms oricum
  • Problema e ca eu te vad acolo.
  • prietene, nu ma lasa :) “你必须在 Stack Overflow 上拥有 20 声望才能在此处交谈”... las nu`ti mai bate capul, ms oricum mare domn
【解决方案3】:

您不能在系统级别从用户输入中做出其他事情。假设您想让用户为链接添加书签(这是 Control + D 所做的),这可以让您到达您想要的位置:

function addBookmark(title,url){ 
  if(window.sidebar){ 
    window.sidebar.addPanel(title, url, ""); 
  } else if(document.all){ 
    window.external.AddFavorite(url, title); 
  } else if((window.opera && window.print) || window.chrome){ 
    // Chrome & Opera do not have an add Favorite function on window
    alert('Press Control+D to bookmark (Command+D for macs) after you click Ok');
    // or something similar
  }
}

然后你绑定点击处理程序来调用函数:

$('#yourLink').on('click', function(e) {
  addBookmark($(this).attr('title'), $(this).attr('href'));
});

【讨论】:

  • 不适用于书签...但我会尝试您的示例...谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2016-03-05
  • 2015-12-09
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
相关资源
最近更新 更多