第一种 按钮控制
首先 创建两个html按钮和一个div并给div一个样式
input type="button" value="左" id="1">
<input type="button" value="右" id="2">
<div id="3">
div {
width: 100px;
height: 100px;
background-color: bisque;
position: absolute;
left: 100px;
top: 100px;
}然后在script中获得div和两个按钮
var left = document.getElementById("2");
var right = document.getElementById("1");
var div = document.getElementById("3");然后添加onclick函数
left.onclick = function () {
}
right.onclick = function () {
}var x = 100;
left.onclick = function () {
x=x+10;
div.style.left = x+"px";
}
right.onclick = function () {
x=x-10;
div.style.left = x+"px";
}<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div { width: 100px; height: 100px; background-color: bisque;
position: absolute; left: 100px; top: 100px; }
</style>
</head>
<body>
<input type="button" value="左" id="1"> <input type="button" value="右" id="2"> <div id="3"> </div>
<script>
var left = document.getElementById("2"); var right = document.getElementById("1");
var div = document.getElementById("3");
var x = 100;
left.onclick = function () { x=x+10; div.style.left = x+"px";
} right.onclick = function () { x=x-10; div.style.left = x+"px"; }
</script>
</body>
</html><div id="3">
</div>
<style>
div {
width: 100px;
height: 100px;
background-color: bisque;
position: absolute;
left: 100px;
top: 100px;
}
</style>在script里面 获得div
var div=document.getElementById("3");然后声明两个变量控制改变div的left和top
立即学习“Java免费学习笔记(深入)”;
var px=100; var py =100;
然后获得键值
document.onkeydown(在document文档对象中,按任何键都会触发此函数)
alert中输出的event.keyCode会对应按键时,当前键相应的事件值(即每一个按键对应为一个键值)
document.onkeydown = function(){
alert(event.keyCode);
}然后通过测试上下左右得到键值,在swich语句中改变div的left和top改变其位置
switch (event.keyCode){
case 37:
px = px-10;
div.style.left = px+"px";
break;
case 38:
py = py-10;
div.style.top = py+"px";
break;
case 39:
px = px+10;
div.style.left = px+"px";
break;
case 40:
py = py+10;
div.style.top = py+"px";
break;
}源码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div { width: 100px; height: 100px;
background-color: bisque; position: absolute; left: 100px;
top: 100px; }
</style>
</head>
<body>
<div id="3"> </div>
<script>
var div=document.getElementById("3");
var px=100;
var py =100;
document.onkeydown = function(){
// alert(event.keyCode);
switch (event.keyCode){ case 37: px = px-10;
div.style.left = px+"px"; break; case 38:
py = py-10; div.style.top = py+"px"; break;
case 39: px = px+10; div.style.left = px+"px";
break; case 40: py = py+10; div.style.top = py+"px"; break; }
}
</script>
</body>
</html>以上就是JavaScript强化教程――DOM编程(两种控制div移动的方法)的内容,更多相关内容请关注PHP中文网(www.php.cn)!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号