1.拖拽事件
1.1基本操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo11</title>
<style type="text/css">
#box {
width: 50px;
height: 50px;
background-color: lightblue;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box");
box.onmousedown = function() {
document.onmousemove = function(event) {
var left = event.clientX;
var top = event.clientY;
box.style.left = left + "px";
box.style.top = top + "px";
}
}
document.onmouseup = function() {
document.onmousedown = null;
document.onmousemove = null;
}
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
1.2进阶
我们发现一个问题,我们形无论我们刚开始在图形的那个位置开始拖拽,最后鼠标都停留在左上角,于是我们想办法能不能使得鼠标停留的位置与我们刚开始相对的位置相同。
我么由两种方案,一种是将初始鼠标移动到特定位置,但是鼠标控制不太现实,于是我们想到将初始的图形在开始移动的时候移动到特定位置。
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box");
box.onmousedown = function(event) {
var ol = event.clientX - box.offsetLeft;
var ot = event.clientY - box.offsetTop;
document.onmousemove = function(event) {
var left = event.clientX - ol;
var top = event.clientY - ot;
box.style.left = left + "px";
box.style.top = top + "px";
}
}
document.onmouseup = function() {
document.onmousedown = null;
document.onmousemove = null;
}
}
</script>
2.滚轮事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滚轮</title>
<style type="text/css">
#box {
width: 300px;
height: 100px;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box");
box.onwheel = function(event){
if(event.wheelDelta > 0 || event.detail < 0) {
box.style.height = box.clientHeight - 10 + "px";
} else {
box.style.height = box.clientHeight + 10 + "px";
}
}
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
3.键盘事件
37: 左
38:上
39:右
40:下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>键盘事件</title>
<style type="text/css">
#box {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box");
document.onkeydown = function(event){
var speed = 10;
if(event.ctrlKey) {
speed = 50;
}
switch(event.keyCode) {
case 37:
box.style.left = box.offsetLeft - speed + "px";
break;
case 38:
box.style.top = box.offsetTop - speed + "px";
break;
case 39:
box.style.left = box.offsetLeft + speed + "px";
break;
case 40:
box.style.top = box.offsetTop +speed + "px";
break;
}
}
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
作者:Beyong
出处:Beyong博客
github地址:https://github.com/beyong2019
本博客中未标明转载的文章归作者Beyong有,欢迎转载,但未经作者同意必须保留此段声明,且在文章明显位置给出原文连接,否则保留追究法律责任的权利。