標籤:
<!DOCTYPE HTML><html lang="en-US"><head><meta charset="UTF-8"><meta name="keywords" content="div移動"><title>div移動</title></head><body> <div id="div" style="width:200px; position:absolute; height:200px; background-color:#F90; "></div><!-- 做一個div 0.0 --></body></html><script type="text/javascript">var div = document.getElementById(‘div‘);document.onmousedown = function(e)//滑鼠點擊事件{e = e || window.event;var tops = document.getElementById(‘div‘).offsetTop;//div四個角的座標(200可變動)var lefts = document.getElementById(‘div‘).offsetLeft;var rights = lefts+200;var bottoms = tops+200;var mousex = e.pageX || e.clientX;//點擊時的滑鼠位置var mousey = e.pagey || e.clientY;var topz = document.getElementById(‘div‘).getBoundingClientRect().top;//擷取div的左上位置var leftz = document.getElementById(‘div‘).getBoundingClientRect().left;if((mousex > lefts && mousex < rights)&&(mousey > tops && mousey < bottoms)){//判斷滑鼠點擊時是否在div中document.onmousemove = function(e)//滑鼠滑動事件{var mousexx = e.pageX || e.clientX;//擷取即時滑鼠位置var mouseyy = e.pagey || e.clientY;var xx = mousexx - mousex;//求移動的距離var yy = mouseyy - mousey;leftzz = leftz + xx;topzz = topz + yy;div.style.left = leftzz +"px";//對div的左上方進行計算,與滑鼠移動的距離相同div.style.top = topzz +"px";}}}document.onmouseup = function(){//滑鼠抬起將滑動事件解除document.onmousemove = null;}</script>
js初學者的div移動