2015-10-15 92 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