2015-10-15 91 views

回答

1

如果要移動的懶格:

<div id="container"> 
    <div id="lazy"></div> 
</div> 

使用此代碼:

var div = document.getElementById('lazy'); 
var container = document.getElementById('container'); 

var me = function(event) { 
    var x = event.clientX, //mouse position 
     w = div.offsetWidth, //width of the lazy div 
     m = 30, //multiplier 
     square = div.getBoundingClientRect(), 
     pxToBox = (x - (w/2 - square.left)), //how far is the mouse from the box? 
     left = m * pxToBox/this.offsetWidth; 
    div.style.left = left + 'px'; //sets the left attribute 
}; 

container.addEventListener('mousemove', me, false); 

家長懶惰的div必須相對於絕對定位是:

#container { 
    position:relative; 
    width:600px; 
    height:400px; 
} 

#lazy { 
    background-color:green; 
    position:absolute; 
    top:0; 
    left:40; 
    width:100px; height:100px; 
} 

這裏是小提琴http://jsfiddle.net/b42a3fhk/

+0

謝謝你的幫助。你太棒了。 – FGDeveloper