首先说明我还是给菜鸟,平时逛逛博客园看看大神的博客!本着分享的心情写下自己之前完成的作品,总体来说还算满意。
看以通过键盘事件和按扭实现背景的移动
不多说上代码
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>图片背景定位</title> 6 <style type="text/css"> 7 .main{ 8 margin: 0 auto; 9 width: 1000px; 10 text-align: center; 11 } 12 #bg{ 13 margin: 0 auto; 14 position: relative; 15 margin-top: 100px; 16 width: 400px; 17 height: 200px; 18 background: url(img/1.jpg) no-repeat; 19 background-position-x: 0px; 20 background-position-y: 0px; 21 } 22 .showimg{ 23 position: absolute; 24 top: 0; 25 left: 0; 26 width: 396px; 27 height: 196px; 28 border: 2px solid red; 29 z-index: 999; 30 } 31 .pageimg{ 32 position: absolute; 33 top: 200px; 34 left: 0; 35 width: 400px; 36 background-color: #FFFFFF; 37 z-index: 999; 38 } 39 40 </style> 41 <script type="text/javascript"> 42 document.onkeydown=function(event){ 43 var e = event || window.event || arguments.callee.caller.arguments[0]; 44 45 if(e && e.keyCode==37){ // enter 键 46 //要做的事情 47 goto(-10,‘background-position-x‘); 48 } 49 50 if(e && e.keyCode==38){ // enter 键 51 //要做的事情 52 //alert("按 38"); 53 goto(-10,‘background-position-y‘); 54 } 55 if(e && e.keyCode==39){ // enter 键 56 //要做的事情 57 goto(10,‘background-position-x‘); 58 } 59 if(e && e.keyCode==40){ // enter 键 60 //要做的事情 61 //alert("按 40"); 62 goto(10,‘background-position-y‘) 63 } 64 65 }; 66 67 68 function getStyle(obj,name){ 69 if(obj.currentStyle){ 70 return obj.currentStyle[name]; 71 }else{ 72 return getComputedStyle(obj,false)[name]; 73 } 74 } 75 76 function goto(step,direction){ 77 var bg = document.getElementById("bg"); 78 //获取当前定位坐标 及下标字符 只要数字 79 var mydirection = (getStyle(bg,direction)).substr(0,(getStyle(bg,direction)).length-2); 80 //取整 81 var speed = parseFloat(mydirection)+parseFloat(step); 82 bg.style[direction] = speed + ‘px‘; 83 } 84 85 </script> 86 87 </head> 88 <body> 89 90 <div class="main"> 91 <input type="button" value="向上移动" id="moveup" onclick="goto(-10,‘background-position-y‘)" /> 92 <input type="button" value="向下移动" id="movedown" onclick="goto(10,‘background-position-y‘)" /> 93 <input type="button" value="向左移动" id="moveleft" onclick="goto(-10,‘background-position-x‘)" /> 94 <input type="button" value="向右移动" id="moveright" onclick="goto(10,‘background-position-x‘)" /> 95 <div id="bg"> 96 <div class="showimg"></div> 97 <div class="pageimg"></div> 98 </div> 99 </div> 100 </body> 101 </html>
时间: 2024-11-05 19:44:39