js
var Drag = (function () { var $this; function drag() { this.ini.apply(this, arguments); } drag.prototype = { ini:function (inside, outside) { $this = this $this.inside = inside; $this.outside = outside; $this._width=$this.outside.innerWidth()-$this.inside.innerWidth() $this._height=$this.outside.innerHeight()-$this.inside.innerHeight() }, position:function (e) { e = e; var x = e.pageX - $this.outside.position().left - $this.inside.innerWidth() / 2 var y = e.pageY - $this.outside.position().top - $this.inside.innerHeight() / 2 if(x<0){x=0} if(x>$this._width){x=$this._width} if(y<0){y=0} if(y>$this._height){y=$this._height} $this.x = x; $this.y = y; $this.inside.html("x:" + $this.x + " y:" + $this.y) }, move:function () { $this.outside.bind("mousemove", function (e) { $this.position(e) $this.inside.css({"left":$this.x + "px", "top":$this.y + "px" }) }) } } return drag; }()) var k = new Drag($(".inside"), $(".outside")) k.move()
html
<div class="outside"> <div class="inside"> fgdfg </div> </div>
css
.outside { position: relative; border: 1px solid #FF0; 700px; height: 500px; } .inside { position: absolute; border: 1px solid #F00; 100px; height: 100px; }
方法很简单,主要试验下js的闭包,模块化设计。