大前端

前端js实现拖拽功能

2023-05-22  本文已影响0人  jack钱

Sortable.js中文网 (sortablejs.com)
以react为例:
index.tsx

import { useEffect, useState } from 'react';
import Sortable from 'sortablejs';
import styles from './index.less';

export default () => {
  const [gridList, setGridList] = useState<any[]>([]);

  useEffect(() => {
    let el = document.getElementById('gridGroup');
    let sortable = Sortable.create(el, {
      // handle: '.handle',
      animation: 150,
      ghostClass: 'blue-background-class',
    });

    let arr: any[] = [];
    for (let i = 0; i < 100; i++) {
      arr.push({
        index: i,
        name: i,
      });
    }
    setGridList(arr);
  }, []);

  return (
    <>
      <div id="gridGroup" className={styles.gridGroup}>
        {gridList.map((item) => (
          <div
            key={item.index}
            className={`${styles.gridSquare} ${item.index === 1 ? 'handle' : ''}`}
          >
            {item.index}
          </div>
        ))}
      </div>
    </>
  );
};

index.less

.gridGroup {
  display: grid;
  grid-auto-flow: row dense;
  grid-gap: 2px;
  grid-template-rows: repeat(10, 1fr);
  grid-template-columns: repeat(10, 1fr);
  width: 100%;
  height: 100%;
  .gridSquare {
    border: 1px dashed #eee;
  }
}
上一篇下一篇

猜你喜欢

热点阅读