Demo 在线地址:
https://sx00xs.github.io/test/42/index.html
---------------------------------------------------------------
ide: vscode
文件格式:.vue
解析:(待补)
<template> <div> <pre> 红色方块为键盘操作区域,您可以进行如下操作: 上:↑ 下:↓ 左:← 右:→ Ctrl + 1 : 背景变为绿色 Ctrl + 2 : 背景变为黄色 Ctrl + 3 : 背景变为蓝色 Ctrl + ↑ : 放大 Ctrl + ↓ : 缩小 </pre> <div class="box" v-moves ref="myBox"></div> </div> </template> <script> import { setInterval, clearInterval } from 'timers'; export default { name:'Navs', directives:{ moves:{ bind(el,binding,vnode){ var timer = null; var bLeft = false; var bTop = false; var bRight = false; var bBottom = false; function handleKeydown(event){ switch(event.keyCode){ case 37: bLeft=true; break; case 38: if(event.ctrlKey){ var oldWidth = el.offsetWidth; var oldHeight = el.offsetHeight; el.style.width = el.offsetWidth * 1.5 + 'px'; el.style.height = el.offsetHeight * 1.5 + 'px'; el.style.left = el.offsetLeft - (el.offsetWidth - oldWidth) / 2 + 'px'; el.style.top = el.offsetTop - (el.offsetHeight - oldHeight) /2 + 'px'; break; } bTop=true; break; case 39: bRight=true; break; case 40: if(event.ctrlKey){ var oldWidth = el.offsetWidth; var oldHeight = el.offsetHeight; el.style.width = el.offsetWidth * 0.75 + 'px'; el.style.height = el.offsetHeight * 0.75 + 'px'; el.style.left = el.offsetLeft - (el.offsetWidth - oldWidth) / 2 + 'px'; el.style.top = el.offsetTop - (el.offsetHeight - oldHeight) / 2 + 'px'; break; } bBottom = true; break; case 49: event.ctrlKey && (el.style.background = 'green'); break; case 50: event.ctrlKey && (el.style.background = 'yellow'); break; case 51: event.ctrlKey && (el.style.background = 'blue'); break; } return false; } function handleKeyup(e){ switch(e.keyCode){ case 37: bLeft = false; break; case 38: bTop=false; break; case 39: bRight=false; break; case 40: bBottom=false; break; } }; function limit(){ var doc=[document.documentElement.clientWidth, document.documentElement.clientHeight]; el.offsetLeft <= 0 && (el.style.left = 0); el.offsetTop <= 0 && (el.style.top = 0); doc[0] - el.offsetLeft - el.offsetWidth <= 0 && (el.style.left = doc[0] - el.offsetWidth + 'px'); doc[1] - el.offsetTop - el.offsetHeight <= 0 && (el.style.top = doc[1] - el.offsetHeight + 'px'); } timer=setInterval(function(){ if(bLeft){ el.style.left=el.offsetLeft - 10 + 'px'; } else if(bRight){ el.style.left = el.offsetLeft + 10 + 'px'; } if(bTop){ el.style.top = el.offsetTop - 10 + 'px'; } else if(bBottom){ el.style.top = el.offsetTop + 10 + 'px'; } limit(); },30) el.__vueKeyDown__ = handleKeydown; el.__vueKeyUp__ = handleKeyup; el.__timer__ = timer; document.addEventListener('keydown',handleKeydown); document.addEventListener('keyup',handleKeyup); }, unbind(el,binding,vnode){ document.removeEventListener('keydown',el.__vueKeyDown__); document.removeEventListener('keyup',el.__vueKeyUp__); delete el.__vueKeyDown__; delete el.__vueKeyUp__; clearInterval(el.__timer__); } } } } </script>