JSFiddle - React, Tailwind, and code Playground
HTML
<h1>图标拖放进文件夹DEMO</h1>
<p>1、你可以先点击右侧文件夹(div)进行层级排序</p>
<p>2、然后拖动下面的图标(小黑方块)到文件夹内</p>
<p id="tip">提示信息:</p>
<div class="app"></div>
<div class="folder folder1" id="folder1">1</div>
<div class="folder folder2" id="folder2">2</div>
<div class="folder folder3" id="folder3">3</div>
CSS
#tip{border:1px solid #000;width:350px;height:24px;line-height:24px}
.app{-moz-user-select:none;-khtml-user-select:none;user-select:none}
.app{position:absolute;z-index:1000;width:100px;height:100px;background:#000;left:100px;top:200px}
.folder{position:absolute;background:#fff;width:600px;height:350px;line-height:350px;text-align:center;border:1px solid #000}
.folder1{z-index:1;right:150px;top:50px}
.folder2{z-index:2;right:250px;top:150px}
.folder3{z-index:3;right:50px;top:250px}
JavaScript
$(function(){
//图标拖动事件
$('.app').on('mousedown',function(e){
var obj = $(this), x, y, mx, my, l, t;
x = e.clientX - obj.offset().left;
y = e.clientY - obj.offset().top;
$(window).on('mousemove',function(e){
mx = e.clientX;
my = e.clientY;
l = e.clientX - x;
t = e.clientY - y;
obj.css({left:l+'px',top:t+'px'});
}).on('mouseup',function(){
var folder = searchFolderGrid(mx, my);
$('.folder').css('background-color','#fff');
if(typeof(folder) != 'undefined'){
$('#'+folder).css('background-color','red').css('z-index',globle_zIndex);
globle_zIndex += 1;
$('#tip').text('提示信息:你已将图标拖放进'+$('#'+folder).text()+'号文件夹内');
}else{
$('#tip').text('提示信息:你已将图标拖放出文件夹');
}
$(this).off("mousemove").off("mouseup");
});
});
//文件夹每次点击z-index递增加1
var globle_zIndex = 4;
$('.folder').click(function(){
$(this).css('z-index',globle_zIndex);
globle_zIndex += 1;
});
//绘制文件夹格子
var folderGrid = function(){
var grid = [];
$('.folder').each(function(){
grid.push({
zIndex: $(this).css('z-index'),
id: $(this).attr('id'),
startY: $(this).offset().top,
endY: $(this).offset().top + $(this).height(),
startX: $(this).offset().left,
endX: $(this).offset().left + $(this).width()
});
});
grid.sort(function(x, y){
return y['zIndex'] - x['zIndex'];
});
return grid;
}
//搜索文件夹格子,返回文件夹ID
var searchFolderGrid = function(x, y){
var grid = folderGrid(), i = 0, j = grid.length, flags = 0, curr;
for(; i < j; i++){
curr = grid[i];
if(x >= curr.startX && x <= curr.endX){
flags++;
...