이 기사에서는 JS에 의해 DIV 이동을 제어하기 위해 키보드를 구현하는 방법에 대해 설명합니다. 참조를 위해 공유하십시오. 특정 분석은 다음과 같습니다.
CSS 스타일 부분 :
다음과 같이 코드를 복사하십시오. <style type = "text/css">
html, body {오버플로 : 숨겨진;}
바디 {마진 : 0; 패딩 : 0;}
pre {색상 : 녹색; 패딩 : 10px 15px; 배경 : #f0f0f0; 테두리 : 1px 점선 #333; font : 12px/1.5 택배 새; 마진 : 12px;}
Span {색상 :#999;}
#box {위치 : 절대; 상단 : 50px; 왼쪽 : 300px; 너비 : 100px; 높이 : 100px; 배경 : 빨간색;}
</스타일>
JS 부분 :
다음과 같이 코드를 복사하십시오. <script type = "text/javaScript">
Window.onload = function ()
{
var obox = document.getElementById ( "box");
var bleft = btop = bright = bbottom = bctrlkey = false;
setInterval (function ()
{
if (bleft)
{
obox.style.left = obox.offsetleft -10 + "px"
}
그렇지 않으면 (밝은)
{
obox.style.left = obox.offsetleft + 10 + "px"
}
if (btop)
{
obox.style.top = obox.offsettop -10 + "px"
}
else if (bbottom)
{
obox.style.top = obox.offsettop + 10 + "px"
}
// 오버플로를 방지합니다
한계();
}, 30);
document.onkeydown = 함수 (이벤트)
{
var event = 이벤트 || Window.event;
bctrlkey = event.ctrlkey;
스위치 (event.keyCode)
{
사례 37 :
bleft = true;
부서지다;
사례 38 :
if (bctrlkey)
{
var oldwidth = obox.offsetWidth;
var oldheight = obox.offsetheight;
obox.style.width = obox.offsetWidth * 1.5 + "PX";
obox.style.height = obox.offsetheight * 1.5 + "px";
obox.style.left = obox.offsetleft- (obox.offsetwidth -Oldwidth) / 2 + "px";
obox.style.top = obox.offsettop- (Obox.offSetheight -Oldheight) / 2 + "px";
부서지다;
}
btop = true;
부서지다;
사례 39 :
Bright = true;
부서지다;
사례 40 :
if (bctrlkey)
{
var oldwidth = obox.offsetWidth;
var oldheight = obox.offsetheight;
obox.style.width = obox.offsetWidth * 0.75 + "PX";
obox.style.height = obox.offsetheight * 0.75 + "px";
obox.style.left = obox.offsetleft- (obox.offsetwidth -Oldwidth) / 2 + "px";
obox.style.top = obox.offsettop- (Obox.offSetheight -Oldheight) / 2 + "px";
부서지다;
}
bbottom = true;
부서지다;
사례 49 :
bctrlkey && (obox.style.background = "green");
부서지다;
사례 50 :
bctrlkey && (obox.style.background = "Yellow");
부서지다;
사례 51 :
bctrlkey && (obox.style.background = "blue");
부서지다;
}
거짓을 반환하십시오
};
document.onkeyup = function (이벤트)
{
스위치 ((이벤트 || 창 .event) .keyCode)
{
사례 37 :
bleft = false;
부서지다;
사례 38 :
btop = false;
부서지다;
사례 39 :
밝은 = 거짓;
부서지다;
사례 40 :
bbottom = false;
부서지다;
}
};
// 오버플로를 방지합니다
함수 한계 ()
{
var doc = [document.documentElement.clientWidth, document.documentElement.clientHeight]
// 왼쪽이 오버플로되는 것을 방지합니다
obox.offsetleft <= 0 && (obox.style.left = 0);
// 상단 오버플로를 방지합니다
obox.offsettop <= 0 && (obox.style.top = 0);
// 오른쪽이 오버플로되는 것을 방지합니다
doc [0] -Bobox.offsetleft -obox.offsetwidth <= 0 && (obox.style.left = doc [0] -Bovox.offsetWidth + "px");
// 하단 오버플로를 방지합니다
Doc [1] -Bobox.offsettop -Obox.offSetheight <= 0 && (obox.style.top = doc [1] -Box.offsetheight + "px")
}
};
</스크립트>
설명 :
상단 : ↑ 다음 : ↓ 왼쪽 : ← 오른쪽 : →
Ctrl + 1 : 배경이 녹색으로 변합니다
Ctrl + 2 : 배경이 노란색으로 변합니다
Ctrl + 3 : 배경이 파란색으로 변경됩니다
ctrl + ↑ : 확대
Ctrl + ↓ : 수축
HTML 부분 :
코드 사본은 다음과 같습니다.
<div id = "box"> </div>
이 기사가 모든 사람의 JavaScript 프로그래밍에 도움이되기를 바랍니다.