美文网首页
js拖拽排序

js拖拽排序

作者: zkzhengmeng | 来源:发表于2025-01-20 17:27 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Drag and Drop Sorting</title>
<style>
   .rank_wrap{
       position: fixed;
       width: 50%;
       height: auto;
       overflow: hidden;
       padding: 10px;
       /* 居中 */
       left: 50%;
       top: 50%;
       transform: translate(-50%, -50%);  
   }
   #sortable-list {
     list-style-type: none;
     margin: 0;
     padding: 0;
     width: 100%;
     box-sizing: border-box;
   }
    
   #sortable-list li {
     background-color: #f9f9f9;
     border: 1px solid #ddd;
     margin: 5px;
     padding: 10px;
     cursor: move;
   }
   #sortable-list li:hover{
       background: #ffc;
   }
   .output{
       padding: 10px;
       color: #999;
       font-size: 14px;
   }
</style>
</head>
<body>
 
<div class="rank_wrap">
    <ul id="sortable-list"> </ul>
    <div id="output" class="output"></div>
</div>
 
<script>
    const list = document.getElementById('sortable-list');
    const output = document.getElementById('output');
    for(let i =0;i<10;i++){
      let str = `<li draggable="true" data-index="${i}">item ${i}</li>`
      list.innerHTML+=str
    }
   list.addEventListener('dragstart', (e) => {
     e.target.style.opacity = '0.6';
     e.dataTransfer.setData('text/plain', e.target.getAttribute('data-index'));
   });
    
   list.addEventListener('dragend', (e) => {
     e.target.style.opacity = '1';
   });
    
   list.addEventListener('dragover', (e) => {
     e.preventDefault();
     e.target.style.border = '1px dashed #ddd';
   });
    
   list.addEventListener('dragleave', (e) => {
     e.target.style.border = '';
   });
    
   list.addEventListener('drop', (e) => {
     e.preventDefault();
     const fromIndex = e.dataTransfer.getData('text/plain');
     const toIndex = Array.from(list.children).indexOf(e.target);
     moveItem(fromIndex, toIndex);
   });
    
   function moveItem(fromIndex, toIndex) {
     const items = Array.from(list.children);
     const draggedItem = items[fromIndex];
    
     items.splice(fromIndex, 1);
     items.splice(toIndex, 0, draggedItem);
    
     list.innerHTML = '';
     items.forEach((item, index) => {
       item.setAttribute('data-index', index);
       list.appendChild(item);
     });
      console.log('拖拽前编号====>>>',fromIndex);    
     console.log('拖拽后编号====>>>',toIndex);   
     output.textContent = '新排序:' + items.map(item => item.textContent).join(', ');
   }
</script>
 
</body>
</html>

相关文章

网友评论

      本文标题:js拖拽排序

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