JS實(shí)現(xiàn)可以用鍵盤方向鍵控制的動畫
更新時(shí)間:2020年12月11日 14:24:10 作者:KindleYoung
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)可以用鍵盤方向鍵控制的動畫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
用JS寫一個(gè)可以用鍵盤方向鍵控制的動畫:
效果如下:

好了,代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
overflow: hidden
}
img {
position: absolute;
top: 0;
left: 10px;
width: 100px;
height: 82px
}
.right {
transform: rotateY(180deg)
}
.top {
transform: rotateZ(45deg)
}
.bottom {
transform: rotateZ(-45deg)
}
</style>
</head>
<body>
<img src="./img//Blue ocean11.png" alt="" class="move-background">
<script>
var oImg = document.querySelector("img");
/* 思路: */
/* 監(jiān)聽鍵盤的事件(<- -> 上 下) */
document.onkeydown = function(e) {
e = e || window.event;
var code = e.which || e.keyCode;
var offset = 10;
switch (code) {
case 37:
console.log("left");
console.log('innerWidth',innerWidth,oImg.offsetLeft);
oImg.className = "";
var left = oImg.offsetLeft - offset;
if (left <= -oImg.offsetWidth) {
left = window.innerWidth;
}
oImg.style.left = left + "px";
break;
case 38:
console.log("top");
oImg.className = "top";
var top = oImg.offsetTop - offset;
if (top <= -oImg.offsetHeight) {
top = window.innerHeight;
}
oImg.style.top = top + "px";
break;
case 39:
console.log("right");
oImg.className = "right";
var left = oImg.offsetLeft + offset;
if (left >= window.innerWidth) {
left = -oImg.offsetWidth;
}
oImg.style.left = left + "px";
break;
case 40:
console.log("bottom");
oImg.className = "bottom";
var top = oImg.offsetTop + offset;
if (top >= window.innerHeight) {
top = -oImg.offsetHeight;
}
oImg.style.top = top + "px";
break;
default:
break;
}
/* 臨界值檢查 */
}
</script>
</body>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
深入理解JavaScript系列(26):設(shè)計(jì)模式之構(gòu)造函數(shù)模式詳解
這篇文章主要介紹了深入理解JavaScript系列(26):設(shè)計(jì)模式之構(gòu)造函數(shù)模式詳解,本文講解了基本用法、構(gòu)造函數(shù)與原型、只能用new嗎?、強(qiáng)制使用new、原始包裝函數(shù)等內(nèi)容,需要的朋友可以參考下2015-03-03
詳解JS中continue關(guān)鍵字和break關(guān)鍵字的區(qū)別
在javascript中continue的作用是退出當(dāng)前次循環(huán),break的作用則是一旦當(dāng)前循環(huán)有break那么直接退出整個(gè)循環(huán)。本文將通過一些示例為大家詳細(xì)講講二者的區(qū)別,感興趣的可以了解一下2022-08-08
JavaScript中split與join函數(shù)的進(jìn)階使用技巧
這篇文章主要介紹了JavaScript中split與join函數(shù)的進(jìn)階使用技巧,split和join通常被用來操作數(shù)組和字符串之間的轉(zhuǎn)換,需要的朋友可以參考下2016-05-05
解決layer彈出層的內(nèi)容頁點(diǎn)擊按鈕跳轉(zhuǎn)到新的頁面問題
今天小編就為大家分享一篇解決layer彈出層的內(nèi)容頁點(diǎn)擊按鈕跳轉(zhuǎn)到新的頁面問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09

