JS每日一题-小demo之JS实现通过键盘方向键操作图片上下左右无缝切换 js键盘上下左右事件

 2022-10-21    359  

有的朋友可能对于“JS每日一题-小demo之JS实现通过键盘方向键操作图片上下左右无缝切换 js键盘上下左右事件”还有很多不明白的地方,下面由77ISP云服务器技术小编为大家讲解一下,下面我们来一起看看吧!

Document

.wrap {
margin: 150px auto;
position: relative;
width: 400px;
height: 300px;
overflow: hidden;
border: 2px solid #000;
} 
.wrap img {
position: absolute;
}



(function(){ var data = ["https://www.php.cn/pic/1.jpg","https://www.php.cn/pic/2.jpg","pic/3.jpg","pic/4.jpg"]; var img = document.querySelectorAll('img'); var now = 0; var next = 0; var imgW = css(img[0],"width"); var imgH = css(img[0],"height"); var isMove = false; document.addEventListener('keyup', function(e) { if(isMove){ return; } switch(e.keyCode){ case 37: //向左 toLeft(); break; case 38: //向上 toUp(); break; case 39: //向右 toRight(); break; case 40: //向下 toDown(); break; } }); function toLeft(){ next = (now + 1)%data.length; init([0,0,0,imgW],{left:-imgW},{left:0}); } function toUp(){ next = (now + 1)%data.length; init([0,0,imgH,0],{top:-imgH},{top:0}); } function toRight(){ next = (now - 1 + data.length)%data.length; init([0,0,0,-imgW],{left:imgW},{left:0}); } function toDown(){ next = (now - 1 + data.length)%data.length; init([0,0,-imgH,0],{top:imgH},{top:0}); } // styles = [0,0,0,0]; // target1 {} //init 初始位置 function init(styles,target1,target2){ isMove = true; img[0].src= data[now]; img[1].src= data[next]; css(img[0],"top",styles[0]); css(img[0],"left",styles[1]); css(img[1],"top",styles[2]); css(img[1],"left",styles[3]); now = next; move(img[0],target1); move(img[1],target2,function(){ isMove = false; }); } // 移动 function move(el,target,callBack){ startMove({ el:el, target:target, type: "easeOut", time: 1000 }); } })(); //动画形式公式 var Tween = { linear: function (t, b, c, d){ return c*t/d + b; }, easeIn: function(t, b, c, d){ return c*(t/=d)*t + b; }, easeOut: function(t, b, c, d){ return -c *(t/=d)*(t-2) + b; }, easeBoth: function(t, b, c, d){ if ((t/=d/2) d){ clearInterval(init.el.timer); init.callBack&&init.callBack(); } else { for(var s in init.target){ var val = Tween[init.type](t,b[s],c[s],d); css(init.el,s,val); } } },20); }

以上就是“JS每日一题-小demo之JS实现通过键盘方向键操作图片上下左右无缝切换 js键盘上下左右事件”的详细内容,更多请关注77isp云服务器技术网其它相关文章!

原文链接:https://77isp.com/post/3437.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。