所以要引入JQUERY框架。
把我的這個控件代碼放到一個js文件裡面直接引入就可以了
控件代碼
代碼如下:
$.fn.myDrag = function() {
var self = $(this);
self.css("position", "absolute");
var p = self.position();
self.css({ left: p.left, top: p.top });
self.mousedown(
function(event) {
// debugger;
self.data("ifDary", "true"); //保存狀態,表示是否可以拖拽
// debugger;
var selfLeft = event.pageX - parseInt(self.css("left")); //計算出鼠標到這個元素的left
var selfTop = event.pageY - parseInt(self.css("top")); //計算出鼠標到這個元素的top
self.data("selfLeft", selfLeft); //保存坐標信息
self.data("selfTop", selfTop);
}
);
$(document).mouseup(
function() {
self.data("ifDary", "false");
//防止窗體飛到外面去
var bWidth = $(window).width();
var bHeight = $(window).height();
var currentleft = parseInt(self.css("left"));
var currenttop = parseInt(self.css("top"));
if (currentleft <= 0)
currentleft = 0;
if (currentleft >= bWidth)
currentleft = bWidth - self.width();
if (currenttop <= 0)
currenttop = 0;
if (currenttop >= bHeight)
currenttop = bHeight - self.height();
self.css({ left: currentleft, top: currenttop });
}
);
$(document).mousemove(function(event) {
var state = self.data("ifDary");
if (state && state == "true") {
var selfLeft = event.pageX - parseInt(self.data("selfLeft")); //計算這個元素的left位置
var selfTop = event.pageY - parseInt(self.data("selfTop"));
self.css({ left: selfLeft, top: selfTop }); //設置這個元素的位置
}
});
return self;
}
javascript代碼
代碼如下:
<script src="../script/jquery-1.3.2.js" type="text/javascript"></script> //這個是JQUERY框架,沒有的自己搜索去到處都是,一腳踩一堆
<script src="myDrag.js" type="text/javascript"></script> //這個是我的那個控件代碼
<script type="text/javascript">
$(function() {
$("#div1").myDrag();
});
</script>
HTML代碼
代碼如下:
<div id="div1" style="background-color: Red; height: 100px; width: 100px;">
點擊拖我吧
</div>