[英]Show div's original position as user moves div across page
我有一個可排序的列表。
當用戶拖動列表項時,我想對該項目的原始 position 進行樣式化,直到用戶停止拖動。
在這種情況下,列表中的空白區域周圍有一個邊框,表示波蘭春天的原始position。
我最初的想法是在每個li
項目后面直接放置一個容器 div。 但是,要使其正常工作,容器 div 需要為position:relative
並且li
項需要為position:absolute
但出於列表的目的, li
項需要為position:relative
。
這是我的相關代碼:
import styled from '@emotion/styled';
const App = styled('div')`
font-family: sans-serif;
font-size: 1.5rem;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
ul {
margin: 0;
padding: 0;
list-style: none; !important
}
ul li {
background-color: #D3D3D3;
padding: 10px 20px;
position: relative;
//the line below does not work
//position: absolute;
display: flex;
line-height: 1;
list-style-type: none;
border-style: solid;
margin-top:10px;
cursor: pointer
}
`;
const Container = styled('div')`
background: red;
border-color: coral;
position: relative;
`;
class DragDropList extends React.Component {
*/ ....*/
onDragStart = (e, index) => {
this.draggedItem = this.state.items[index];
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', e.target.parentNode);
//e.dataTransfer.setDragImage(e.target.parentNode, 20, 20);
};
onDragOver = index => {
const draggedOverItem = this.state.items[index];
// if the item is dragged over itself, ignore
if (this.draggedItem === draggedOverItem) {
return;
}
// filter out the currently dragged item
let order = this.state.order.filter(item => item !== this.draggedItem);
// add the dragged item after the dragged over item
order.splice(index, 0, this.draggedItem);
this.setState({ order });
};
onDragEnd = index => {
this.draggedIdx = null;
// filter out the currently dragged item
let items = this.state.order;
this.setState({ items });
};
render() {
return (
<App>
<main>
<ul>
{this.state.items.map((item, idx) => (
<div>
<Container>
<li
key={item + `idx`}
onDragOver={() => this.onDragOver(idx)}
draggable
onDragStart={e =>
this.onDragStart(e, idx)
}
onDragEnd={() => this.onDragEnd(idx)}
>
<div
draggable
onDragStart={e =>
this.onDragStart(e, idx)
}
onDragEnd={() =>
this.onDragEnd(idx)
}
>
<span
className="content"
style={{ cursor: 'pointer' }}
>
{item}
</span>
</div>
</li>
</Container>
</div>
))}
</ul>
</main>
</App>
);
}
}
這是一個沙箱: https://codesandbox.io/s/black-dust-hqm2t?fontsize=14
不確定這是否是最好的方法,但我通過將拖動的索引存儲在 state 中並添加一個簡單的條件來更改拖動項的 CSS 並添加一個簡單的條件來更改className
如果它與拖動的索引匹配。 為了達到您發布的確切效果,可能需要更多的 CSS 技巧或其他條件渲染,但這應該涵蓋基本功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.