2012-08-18 43 views
0

我有兩個簡單的div,其中一個包含內部的其他移動和限制運動

div#numero{ 
    position:absolute; 
    background-color:#ff3324; 
    border-style: solid; 
    border-width: 2px; 
    width:30px; 
    height:30px; 
    font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif; 
    font-size:1em; 
    line-height: 30px; 
    text-align:center; 
    margin-left:0; 
    margin-right:0; 
}; 

div#cont{ 
    position:relative; 
    border-style: solid; 
    border-width: 2px; 
    width:500px; 
    height:500px; 
    margin-left:auto; 
    margin-right:auto; 
    padding:0; 
} 

我要移動的第一個內的div容器

<div id = "cont" onmousemove = "moveDiv()"> 
     <div id = "numero"> 
      1   
     </div> 
    </div> 
內部

其中moveDiv簡直是

function moveDiv() 
{ 
    var e = document.all["numero"] 
    x = window.event.clientX ; 
    y = window.event.clientY ; 

    e.style.left = x +"px"; 
    e.style.top = y +"px"; 


} 

代碼不工作,我想。鼠標位置和內部div(數字)移動的位置之間有很大的偏移量。我也想限制容器div內的移動。 一些幫助,將不勝感激。

謝謝。

+0

做出的jsfiddle:http://www.jsfiddle.com,人們會幫你 – 2012-08-18 19:18:33

+0

看到http://stackoverflow.com/questions/11979784/why-is- pageX屬性和 - pagey相對至包裝而不是文檔/ 11979955#11979955 – Musa 2012-08-18 19:23:22

回答

0

http://jsfiddle.net/enHmy/

添加以下代碼的HTML代碼後

document.getElementById('cont').onmousemove=moveDiv; 

然後你的功能應該是:

function moveDiv(e){ 
    if(!e){e=window.event;} 
    var el = document.getElementById('numero'); 
    x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2; 
    y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2; 

    el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px"; 
    el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px"; 
} 

但讓我們來分析你的函數:

爲什麼你使用document.all["numero"]?這是非常古老的,不符合兼容的瀏覽器,現在它是document.getElementById('numero');。您可以使用window.event。這適用於IE,但你應該通過一個參數e(事件),如果e未定義(它是舊的IE),我們將其設置爲window.event

當你關閉一個CSS規則時,不要在}之後寫一個分號。

編輯:

如果滾動頁面,numero位置不正確。

固定在http://jsfiddle.net/enHmy/1/

function moveDiv(e){ 
    if(!e){e=window.event;} 
    var el = document.getElementById('numero'); 
    x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2+getScroll('Left'); 
    y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2+getScroll('Top'); 

    el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px"; 
    el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px"; 
} 
function getScroll(dir){ 
    return Math.max(document.body["scroll"+dir]||0,document.documentElement["scroll"+dir]||0); 
}