Created
October 4, 2023 18:14
-
-
Save danyelhenrique/a937923ff354099f6806d0228b28c42c to your computer and use it in GitHub Desktop.
dragitem javascript html css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <style> | |
| /* Estilize o botão arrastável */ | |
| .draggable-button { | |
| width: 100px; | |
| height: 40px; | |
| background-color: #007bff; | |
| color: #fff; | |
| text-align: center; | |
| line-height: 40px; | |
| cursor: grab; | |
| position: absolute; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <!-- Botão que pode ser arrastado --> | |
| <button id="dragButton" class="draggable-button" draggable="true">Arraste-me</button> | |
| <script> | |
| const dragButton = document.getElementById('dragButton'); | |
| // Função para criar um clone do botão | |
| function createClone(event) { | |
| const clone = dragButton.cloneNode(true); // Cria um clone do botão | |
| clone.style.position = 'fixed'; | |
| clone.style.left = (event.clientX - 50) + 'px'; // Define a posição X do clone com base na posição do mouse | |
| clone.style.top = (event.clientY - 20) + 'px'; // Define a posição Y do clone com base na posição do mouse | |
| clone.addEventListener('dragend', e => { | |
| clone.style.left = (e.clientX - 50) + 'px'; // Define a posição X do clone com base na posição do mouse | |
| clone.style.top = (e.clientY - 20) + 'px'; // | |
| }) | |
| document.body.appendChild(clone); // Adiciona o clone ao corpo do documento | |
| } | |
| // Evento quando o botão começa a ser arrastado | |
| dragButton.addEventListener('dragstart', (event) => { | |
| event.dataTransfer.setData('text/plain', ''); // Necessário para tornar o elemento arrastável no Firefox | |
| }); | |
| // Evento quando o botão é solto após ser arrastado | |
| dragButton.addEventListener('dragend', (event) => { | |
| console.log('event', event) | |
| // Aqui criamos o clone apenas quando o botão é solto (dragend) | |
| createClone(event); | |
| dragButton.style.left = '0'; | |
| dragButton.style.top = '0'; | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment