jquery ui 拖拽并创建新元素实现放置
emer 发布于 2018-8-8 11:50 2346 次阅读
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI 放置(Droppable) - 购物车演示</title>
<link rel="stylesheet" href="./jquery-ui1.css">
<script src="./jquery-1.9.1.js"></script>
<script src="./jquery-ui1.js"></script>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
table {
font-size: 1em;
}
.ui-draggable, .ui-droppable {
background-position: top;
}
h1 { padding: .2em; margin: 0; }
#products { float:left; width: 500px; margin-right: 2em; }
#cart { width: 200px; float: left; margin-top: 1em; }
/ 定义列表样式,以便最大化 droppable /
#cart ol { margin: 0; padding: 1em 0 1em 3em; }
</style>
</head>
<body>
<div id="products">
<h1 class="ui-widget-header">产品</h1>
<div id="catalog">
<h2><a href="#">T-Shirts</a></h2>
<div>
<ul>
<li id="add"><span>点我创建</span></li>
<li>Cheezeburger Shirt</li>
<li>Buckit Shirt</li>
</ul>
</div>
<h2><a href="#">Bags</a></h2>
<div>
<ul>
<li>Zebra Striped</li>
<li>Black Leather</li>
<li>Alligator Leather</li>
</ul>
</div>
<h2><a href="#">Gadgets</a></h2>
<div>
<ul>
<li>iPhone</li>
<li>iPod</li>
<li>iPad</li>
</ul>
</div>
</div>
</div>
<div id="cart">
<h1 class="ui-widget-header">购物车</h1>
<div class="ui-widget-content">
<ol>
<li class="placeholder">添加产品到这里</li>
</ol>
</div>
</div>
<style>
.color1{
color:red;
}
</style>
<script>
$(function() {
$( "#catalog" ).accordion();
$( "#catalog li" ).draggable({
appendTo: "body",
helper: "clone"
});
$( ".color1" ).draggable();
$(document).on('mousedown', "#add", function(event) {
event.preventDefault();
console.log(1);
// $("<li class='color1'>我是创建的</li>").draggable({
// appendTo: "body",
// helper: "clone"
// })
elem = $('<div/>').addClass('color1').text('我是创建的');
elem.draggable({
appendTo: "body",
helper: "clone"
});
$('#add').append(elem);
});
$( "#cart ol" ).droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function( event, ui ) {
$( this ).find( ".placeholder" ).remove();
$( "<li class='color1'></li>" ).text( ui.draggable.find(".color1").text()).appendTo( this );
$("#catalog .color1").remove();
}
}).sortable({
items: "li:not(.placeholder)",
sort: function() {
// 获取由 droppable 与 sortable 交互而加入的条目
// 使用 connectWithSortable 可以解决这个问题,但不允许您自定义 active/hoverClass 选项
$( this ).removeClass( "ui-state-default" );
}
});
});
</script>
</body>
</html>