JS设置自定义快捷键并实现图片上下左右移动
ChenChaim 人气:0JS代码实现自定义热键
实现功能:
1.自定义上下左右键
2.使用自定义热键或者使用键盘上下左右键移动图片
效果图:
步骤1:
HTML代码:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>使用自定义按键实现图片移动</title> <style type="text/css"> table { border-collapse: collapse; } </style> <script src="js/key.js"></script> </head> <body> <img id="img" src="img/Koala.jpg" align="center" style="width: 80px;height: 80px;position: absolute;left:0px;top: 0px" /> <table align="center" border="1"> <tr> <td align="center" colspan="2">修改上下左右键</td> </tr> <tr> <td>上:</td> <td><input type="text" onkeyup="myFunction('up')" maxlength="1"></td> </tr> <tr> <td>下:</td> <td><input type="text" onkeyup="myFunction('down')" maxlength="1"></td> </tr> <tr> <td>左:</td> <td><input type="text" onkeyup="myFunction('left')" maxlength="1"></td> </tr> <tr> <td>右:</td> <td><input type="text" onkeyup="myFunction('right')" maxlength="1"></td> </tr> <tr> <td align="center" colspan="2"><input type="button" value="确定" onclick="confirm()" /></td> </tr> </table> </body> </html>
步骤2:
JS:
var up, down, left, right; var up1, down1, left1, right1; var obj = document.getElementById("img"); obj.left = 0; obj.top = 0; //通过设置四个不同参数来进行判断 function myFunction(str) { var Key = window.event.keyCode; //当str=设置的参数时把key赋值给up1 if (str == "up") { up1 = Key; } if (str == "down") { down1 = Key; } if (str == "left") { left1 = Key; } if (str == "right") { right1 = Key; } } //确定函数事件 function confirm() { //把up1赋值给up up = up1; down = down1; left = left1; right = right1; alert("您设置的热键键值为:" + up + ";" + down + ";" + left + ";" + right); fkey(); } function fkey() { console.log(event.keyCode); var Key = window.event.keyCode; //获取你自定义的键和键盘上下左右键都可以用 if (Key == 37 || Key == parseInt(left)) { //左 obj.left -= 80; } if (Key == 38 || Key == parseInt(up)) { //上 obj.top -= 80; } if (Key == 39 || Key == parseInt(right)) { //右 obj.left += 80; } if (Key == 40 || Key == parseInt(down)) { //下 obj.top += 80; } obj.style.left = obj.left + "px", obj.style.top = obj.top + "px"; } document.onkeydown = fkey;
总结
以上所述是小编给大家介绍的JS设置自定义快捷键并实现图片上下左右移动,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
加载全部内容