如何像Javascript中的浏览器标签一样拖放?

disho6za  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(149)

有人能告诉我这个效果的名称是用在浏览器标签?
我用HTML、CSS和Javascript把标签做得像浏览器一样,但我想在标签之间拖动,但我唯一能做的就是拖放,没有那种视觉效果。

qv7cva1a

qv7cva1a1#

请参考this page以获得更多的解释。我给予你一个简单的例子,因为你没有描述你的HTML。

document.addEventListener('DOMContentLoaded', (event) => {
  function handleDragStart(e) {
    this.style.opacity = '0.4';

    dragSrcEl = this;

    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
    e.dataTransfer.setData('text/plain', this.id);
  }

  function handleDragEnd(e) {
    this.style.opacity = '1';

    items.forEach(function (item) {
      item.classList.remove('over');
    });
  }

  function handleDragOver(e) {
    e.preventDefault();
    return false;
  }

  function handleDragEnter(e) {
    this.classList.add('over');
  }

  function handleDragLeave(e) {
    this.classList.remove('over');
  }
  
  function handleDrop(e) {
    e.stopPropagation();

    if (dragSrcEl !== this) {
      dragSrcEl.innerHTML = this.innerHTML;
      dragSrcEl.id = this.id;
      this.innerHTML = e.dataTransfer.getData('text/html');
      this.id = e.dataTransfer.getData('text/plain');
    }

    return false;
  }

  let items = document.querySelectorAll('.container .box');
  items.forEach(function(item) {
    item.addEventListener('dragstart', handleDragStart);
    item.addEventListener('dragover', handleDragOver);
    item.addEventListener('dragenter', handleDragEnter);
    item.addEventListener('dragleave', handleDragLeave);
    item.addEventListener('dragend', handleDragEnd);
    item.addEventListener('drop', handleDrop);
  });
  
  let pages = [...document.getElementsByClassName('box')];
  
  $('.box').click(function(e) {
    let id = this.id;
    $('.page').hide();
    $(`#${id}-page`).show();
  });
});
.container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}

.box {
  border: 3px solid #666;
  background-color: #ddd;
  border-radius: .5em;
  padding: 10px;
  cursor: move;
}

.box:hover {
  background-color: #00BFFF;
}

.box.over {
  border: 3px dotted #666;
}

.page {
  width: 400px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div id="A" draggable="true" class="box">A (Drag Me)</div>
  <div id="B" draggable="true" class="box">B (Drag Me)</div>
  <div id="C" draggable="true" class="box">C (Drag Me)</div>
</div>
<div id="A-page" class="page">
  Hello, A
</div>
<div id="B-page" class="page" style="display: none;">
  Hello, B
</div>
<div id="C-page"  class="page" style="display: none;">
  Hello, C
</div>

相关问题