在web页面中,需要改变多个元素的位置,可以通过元素拖动来实现。HTML5中加入了一个全局属性draggable,通过设置true/false来控制元素是否可拖动。
下面以图片拖动为例,用jQuery来实现:页面上有多个图片,把一个图片拖动到其他两个图片中间,就可以将这个图片的位置插入到两图之间。
复制代码 代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
.img-div img {
width:200px;
height:200px;
float: left;
}
.img-div {
float: left;
}
.drop-left,.drop-right {
width: 50px;
height: 200px;
float: left;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// 正在拖动的图片的父级DIV
var $srcImgDiv = null;
// 开始拖动
$(".img-div img").bind("dragstart", function() {
$srcImgDiv = $(this).parent();
});
// 拖动到.drop-left,.drop-right上方时触发的事件
$(".drop-left,.drop-right").bind("dragover", function(event) {
// 必须通过event.preventDefault()来设置允许拖放
event.preventDefault();
});
// 结束拖动放开鼠标的事件
$(".drop-left").bind("drop", function(event) {
event.preventDefault();
if($srcImgDiv[0] != $(this).parent()[0]) {
$(this).parent().before($srcImgDiv);
}
});
$(".drop-right").bind("drop", function(event) {
event.preventDefault();
if($srcImgDiv[0] != $(this).parent()[0]) {
$(this).parent().after($srcImgDiv);
}
});
});
</script>
</head>
<body>
<div>
<div></div>
<img src="http://www.vevb.com/uploads/allimg/140514/10023R924_1.jpg" draggable="true">
<div></div>
</div>
<div>
<div></div>
<img src="http://www.vevb.com/uploads/allimg/140514/100254V91_0.jpg" draggable="true">
<div></div>
</div>
<div>
<div></div>
<img src="http://www.vevb.com/uploads/allimg/140514/10023R924_0.jpg" draggable="true">
<div></div>
</div>
<div>
<div></div>
<img src="http://www.vevb.com/uploads/allimg/140514/1002226213_1.jpg" draggable="true">
<div></div>
</div>
</body>
</html>
新闻热点
疑难解答
图片精选