猿问

jquery如何捕获用户按下了Ctrl+d键?

当用户添加一个网站到收藏夹时(按下Ctrl+d键)时触发一个事件,如下代码是网上摘抄的一段用Ctrl+Enter键发送内容的js代码,稍微修改了一下,将“Enter”键ASCII码13改为“d”键ASCII码100,为什么一直没有反应?


<script>

$(document).keypress(function(e){ 

if(e.ctrlKey && e.which == 100 || e.which == 10) 

    { 

        triggerSomething();

    }

})

function triggerSomething()

    {

        document.write('add bookmark successfully!');

    }

</script>


12345678_0001
浏览 685回答 2
2回答

幕布斯6054654

$.ctrl = function(key, callback, args) {&nbsp; &nbsp; var isCtrl = false;&nbsp; &nbsp; $(document).keydown(function(e) {&nbsp; &nbsp; &nbsp; &nbsp; if(!args) args=[];&nbsp; &nbsp; &nbsp; &nbsp; if(e.ctrlKey) isCtrl = true;&nbsp; &nbsp; &nbsp; &nbsp; if(e.keyCode == key.charCodeAt(0) && isCtrl) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback.apply(this, args);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;//you can remove this line if you need bookamrk&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }).keyup(function(e) {&nbsp; &nbsp; &nbsp; &nbsp; if(e.ctrlKey) isCtrl = false;&nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;};$.ctrl('D', function() {&nbsp; &nbsp;triggerSomething();});function triggerSomething() {&nbsp; &nbsp; document.write('add bookmark successfully!');}其实你是弄错了 D 的 ASCII 码和事件类型,你先测试下:$(document).keydown(function(e) {&nbsp; &nbsp; alert(e.which);})此时你点击 D 键,你会发现是以大写 D 的值为准,为68。所以你这么写:$(document).keydown(function(e){&nbsp;&nbsp; &nbsp; if(e.ctrlKey && e.which == 68)&nbsp;&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; triggerSomething();&nbsp; &nbsp; }})function triggerSomething(){&nbsp; &nbsp; document.write('add bookmark successfully!');}上面那段代码可以 handle 更多的 ctrl + key 事件,如果在你的项目里有很多地方会出现 ctrl + key,那么可以把第一段代码当做一个 plugin 来用,如果只有这一处用到的话,就用下面这段吧。

至尊宝的传说

键盘上的&nbsp;ASCII&nbsp;码以大写为准, 所以&nbsp;D&nbsp;的&nbsp;SACII&nbsp;码并不是&nbsp;100&nbsp;而是&nbsp;68.
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答