使用方法
const container = document.getElementById('container');
const fake = document.getElementById('fake');
const margin = 10;
let divs = ['苦力吧','苦力娃','素材下载','网页素材','html模板','网址导航', '源码工具'].map(txt => {
const d = document.createElement('div');
d.classList.add('block');
d.classList.add(txt);
Object.assign(d.style,{
margin: margin + 'px',
})
d.innerHTML = txt;
container.appendChild(d);
return d;
});
divs.forEach((d,startidx) => {
d.addEventListener('mousedown',()=>{
const x0 = container.getBoundingClientRect().x;
const y0 = container.getBoundingClientRect().y;
const others = divs.filter(d2 => d !== d2);
const positions = others.map(d => d.getBoundingClientRect().x);
const widths = others.map(d => d.getBoundingClientRect().width);
let moved = false;
let finalpos = d.getBoundingClientRect().x;
let finalidx = startidx;
const selfClone = d.cloneNode(true);
const clones = [];
function movedCBs(){
Object.assign(selfClone.style,{
left: d.getBoundingClientRect().x + 'px',
top: d.getBoundingClientRect().y + 'px',
position: 'fixed',
margin: 0,
'z-index': 2
})
fake.appendChild(selfClone);
container.classList.add('hidden');
others.forEach((d,i) => {
const position = positions[i];
const clone = d.cloneNode(true);
Object.assign(clone.style,{
position: 'fixed',
left: position + 'px',
top: y0 + margin + 'px',
transition: '.2s',
margin: 0,
})
fake.appendChild(clone);
clones.push(clone);
});
}
function transitionEnd(){
fake.innerHTML = '';
container.classList.remove('hidden');
d.parentNode.removeChild(d);
console.log(finalidx)
container.insertBefore(d, container.children[finalidx]);
divs = Array.from(container.children);
}
function move(e){
if (!moved){
movedCBs();
moved = true;
}
const posx = selfClone.getBoundingClientRect().x + e.movementX
Object.assign(selfClone.style,{
left: posx + 'px',
top: selfClone.getBoundingClientRect().y + e.movementY + 'px'
})
let pos = x0 + margin;
let counter;
let spliced = false;
for (counter=0; counter<widths.length; counter++){
const nextpos = pos + widths[counter] + margin*2;
if (!spliced && Math.abs(nextpos - posx) >= Math.abs(pos - posx)){
spliced = true;
finalpos = pos;
finalidx = counter;
}
Object.assign(clones[counter].style,{
left: pos + (spliced ? selfClone.getBoundingClientRect().width + margin*2 : 0) + 'px'
})
pos = nextpos;
}
if (!spliced){
finalpos = pos;
finalidx = counter;
}
}
document.addEventListener('mousemove', move );
document.addEventListener('mouseup', ()=>{
document.removeEventListener('mousemove',move);
if (!moved) return;
Object.assign(selfClone.style,{
transition: '.2s'
});
setTimeout(()=>{
Object.assign(selfClone.style,{
left: finalpos + 'px',
top: y0 + margin + 'px'
});
},0)
setTimeout(transitionEnd, 200)
},{once:true})
})
})
站长提示:
1. 苦力吧素材官方QQ群:
950875342
2. 平台上所有素材资源,需注册登录会员方能正常下载。
3. 会员用户积极反馈网站、素材资源BUG或错误问题,每次奖励
2K币。
4. PHP源码类素材,如需协助安装调试,或你有二次开发需求,可联系苦力吧客服。
5. 付费素材资源,需充值后方能下载,如有任何疑问可直接联系苦力吧客服