博客> JavaScript强化教程——DOM编程(两种控制div移动的方法)
JavaScript强化教程——DOM编程(两种控制div移动的方法)
2019-08-23 10:44 评论:0 阅读:666 哟猫Intry
js html5

本文为H5EDU机构官方HTML5培训教程,主要介绍:JavaScript强化教程——DOM编程(两种控制div移动的方法)

第一种 按钮控制 首先 创建两个html按钮和一个div并给div一个样式 input type="button" value="左" id="1"> <input type="button" value="右" id="2">

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 () { } 设置一个变量,控制div的left改变 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"; } 源码: <html lang="en"> <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">
[removed] 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"; } [removed] </body> </html> 第二种,键值控制 同样在html中创建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 var px=100; var py =100; 然后获得键值 [removed](在document文档对象中,按任何键都会触发此函数) alert中输出的event.keyCode会对应按键时,当前键相应的事件值(即每一个按键对应为一个键值) [removed] = 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; } 源码: <html lang="en"> <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>
[removed] var div=document.getElementById("3"); var px=100; var py =100; [removed] = 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; } } [removed] </body> </html>[ Enter your link description here: ](http://www.h5edu.cn/htm/step/h5edu_44.html)
收藏
0
sina mail 回到顶部