网页上有很多拖曳的操作,比如拖动树状列表,可拖曳的图片等。
1.原生拖放实现
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - Default functionality</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="external nofollow" > <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <style> .drag{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left:0;
top:0;
}
</style> <script> $(function() {
var _move = false;
//判断目标对象书否处于移动状态 var _x, _y;
//鼠标离控件左上角的相对x.y坐标 $('.drag').click(function(event) {
}
).mousedown(function(e) {
//当按下鼠标左键时 _move = true;
//标记移动为true,开始移动 _x = e.pageX - parseInt($('.drag').css('left'));
//得到左上角的x的位置 _y = e.pageY - parseInt($('.drag').css('top'));
//得到左上角的y的位置 $('.drag').fadeTo('20', 0.5);
//单击后开始拖动 }
);
$(document).mousemove(function(e) {
//监听鼠标移动 if(_move) {
var x = e.pageX - _x;
//计算移动的距离 var y = e.pageY - _y;
$('.drag').css({
top:y, left:x}
);
}
}
).mouseup(function() {
_move = false;
$('.drag').fadeTo('fast', 1);
}
);
}
);
</script></head><body> <div class="drag"></div></body></html>
2 jQuery UI draggable实现拖放
自行实现拖曳方法比较负责,jQuery UI提供了可拖曳的事件,允许用户非常简单的为一个div添加拖曳效果。
jQuery UI主要通过draggable事件来实现拖曳功能。
<script> $(document).ready(function(e) {
$('.drag').draggable({
cursor: 'move'}
);
$('#enable').click(function(e) {
$('.drag').draggable('enable');
}
);
$('#disable').click(function(event) {
$('.drag').draggable('disable');
}
);
$('#deatroy').click(function(event) {
$('.drag').draggable('destroy');
}
);
}
) </script></head><body> <button id="enable">enable</button> <button id="disable">disable</button> <button id="destroy">destroy</button> <div class="drag"> <p>请拖动我!</p> </div></body>
关于draggable的API可以参考draggalbe API
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!