我有一个基本数量字段,并希望允许用户根据键盘向上/向下增加/减少此输入框中的数字.
继续之后:关于键盘代码https://stackoverflow.com/a/375426/560287的EndangeredMassa答案如何将其添加到键盘功能中?
var keynum = 0; if(window.event) { keynum = e.keyCode; } // IE (sucks) else if(e.which) { keynum = e.which; } // Netscape/Firefox/Opera if(keynum == 38) { // up //Move selection up } if(keynum == 27) { // down //Move selection down }
解决方法
//cache our input since we will be working with it each time an arrow key is pressed var $input = $('input'); //bind the the `keydown` event for the `document` object which will catch all `keydown` events that bubble up the DOM $(document).on('keydown',function (event) { //up-arrow (regular and num-pad) if (event.which == 38 || event.which == 104) { //make sure to use `parseInt()` so you can numerically add to the value rather than concocting a longer string $input.val((parseInt($input.val()) + 1)); //down-arrow (regular and num-pad) } else if (event.which == 40 || event.which == 98) { $input.val((parseInt($input.val()) - 1)); } });
这是一个演示:http://jsfiddle.net/QRNP8/1/
请注意,jQuery将charCode / keyCode属性规范化为event.which:
Query normalizes the following properties for cross-browser
consistency:06001