<h1 class="t_rt"> 鼠标拖动层封装类 </h1> <h2> 效果预览 </h2>
<h2> 源代码 </h2>
<textarea id="sourse"> function dragClass(){ this.mouseState = document.all ? 1 : 0 ; this.x; this.y; this.dragId = null; this.index = 100; document.onselectstart = function(){return false;}; } dragClass.prototype = { dragStar:function(dragId,moveId){//拖动入口函数 var _this = this; _this.$(dragId).style.cursor = "move"; _this.$(dragId).onmousedown = function(e){ var e = e ? e : event; //_this.$(moveId).style.zIndex = _this.index ; if(e.button == _this.mouseState) { _this.setDragInfo(e,moveId,moveId); _this.dragPro(moveId); } }, _this.$(moveId).onmousedown = function(e){ _this.$(moveId).style.zIndex = _this.index ; }, _this.$(dragId).onmouseup = function(){ _this.clearDragId(); } document.onmouseup = function(){ _this.clearDragId(); } }, setDragInfo:function(e,dragId,moveId){//拖动初始化 this.x = e.clientX; this.y = e.clientY; this.dragId = dragId; if(this.$(moveId).style.position != "absolute") { this.$(moveId).style.width = this.$(moveId).offsetWidth "px"; this.$(moveId).style.height = this.$(moveId).offsetHeight "px"; this.$(moveId).style.position = "absolute"; this.$(moveId).style.left = this.$(moveId).offsetLeft "px"; this.$(moveId).style.top = this.$(moveId).offsetTop "px"; } }, clearDragId:function(){ //清除拖动ID this.dragId = null; }, dragPro:function(moveId){ var _this = this; document.onmousemove = function(e){ var e = e ? e : event; if(e.button == _this.mouseState && _this.dragId != null) { var x = e.clientX; var y = e.clientY; //_this.$(moveId).style.left = (_this.$(moveId).offsetLeft (x - _this.x)) "px"; //_this.$(moveId).style.top = (_this.$(moveId).offsetTop (y - _this.y)) "px"; _this.$(moveId).style.left = (parseInt(_this.$(moveId).style.left) (x - _this.x)) "px"; _this.$(moveId).style.top = (parseInt(_this.$(moveId).style.top) (y - _this.y)) "px"; _this.x = x; _this.y = y; //alert(_this.$(dragId).style.left); } } }, $:function(o){//获取对象 if(typeof(o) == "string") { if(document.getElementById(o)) { return document.getElementById(o); } else { alert("errId "" o ""!"); return false; } } else { return o; } } } </textarea>
<h2> 使用方法 </h2>
1.把以上代码引进你的页面 <script type="text/javascript" src="dragClass.js"></script>
2.在页面的"</body>"标签前加入以下代码:
<script type="text/javascript">
window.onload = function(){
var c = new dragClass();//创建对象
c.dragStar("拖动id","移动层id");
}
</script>
其中sd方法中的参数为:
参数一 "拖动id":鼠标经过时候鼠标样式变成移动样式模样的元素的id
参数二 "移动层id":即将移动的元素的id
<span class="red">3.建议移动层是绝对定位(position:absolute;).</span>