美文网首页大前端
前端js实现拖拽功能

前端js实现拖拽功能

作者: jack钱 | 来源:发表于2023-05-22 17:03 被阅读0次

    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;
      }
    }
    

    相关文章

      网友评论

        本文标题:前端js实现拖拽功能

        本文链接:https://www.haomeiwen.com/subject/tnrtedtx.html