AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79493546
Accepted
Milos Stojanovic
Milos Stojanovic
Asked: 2025-03-08 06:06:30 +0800 CST2025-03-08 06:06:30 +0800 CST 2025-03-08 06:06:30 +0800 CST

A div arrastável é fixada no lado direito da tela até que a largura máxima seja atingida durante o arrasto

  • 772

Estou fazendo uma extensão do Chrome. Estou tentando fazer o pop-up ser arrastável e poder movê-lo pela tela. Consigo movê-lo, mas ele fica preso no lado direito da tela até chegar a max-width. O que estou fazendo errado?

Aqui está um código simplificado.

const popup = document.getElementById("popup");
const dragBtn = document.getElementById("drag-btn");

let offsetX, offsetY, isDragging = false;

dragBtn.addEventListener("mousedown", (e) => {
    isDragging = true;
    offsetX = e.clientX - popup.offsetLeft;
    offsetY = e.clientY - popup.offsetTop;
});

document.addEventListener("mousemove", (e) => {
    if (isDragging) {
        popup.style.left = `${e.clientX - offsetX}px`;
        popup.style.top = `${e.clientY - offsetY}px`;
    }
});

document.addEventListener("mouseup", (e) => {
    isDragging = false;
});
#popup {
    position: fixed;
    top: 20px;
    right: 20px;
    min-width: 350px;
    max-width: 500px;
    background: var(--dark-bg, #222);
    color: var(--dark-text, #fff);
    border: 1px solid #333;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.4);
    padding: 15px;
    border-radius: 8px;
    z-index: 10000;
}

#popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

#popup-title {
    font-size: 14px;
    font-weight: bold;
}

button {
    border: none;
    cursor: pointer;
    border-radius: 4px;
    font-size: 16px;
    width: 26px;
    height: 26px;
    text-align: center;
    padding: 0;
}

#drag-btn {
    background: #326042;
    color: white;
    cursor: grab;
}

#theme-btn {
    background: #ef713b;
    color: white;
}

#close-btn {
    background: #ff5252;
    color: white;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Song Lyrics Finder</title>
    <link rel="stylesheet" href="src/style.css">
</head>
<body>
    <div id="popup">
        <div id="popup-header">
            <p id="popup-title">Song Lyrics Finder (from Genius.com)</p>
            <div style="display: flex; align-items: center; gap: 5px;">
                <button id="drag-btn">✥</button>
                <button id="theme-btn">&#9681;</button>
                <button id="close-btn">&#11199;</button>
            </div>
        </div>
    </div>
</body>
</html>

javascript
  • 1 1 respostas
  • 51 Views

1 respostas

  • Voted
  1. Best Answer
    Ori Drori
    2025-03-08T06:13:18+08:002025-03-08T06:13:18+08:00

    Como o elemento tem um rightvalor, e você está alterando o leftvalor, você está esticando o elemento até que ele atinja o tamanho máximo.

    Eu mudaria a posição usando transform em vez disso. Além de não temperar com a largura do elemento, o desempenho geralmente é melhor (veja nesta resposta do SO ):

    const popup = document.getElementById("popup");
    const dragBtn = document.getElementById("drag-btn");
    
    let offsetX, offsetY, isDragging = false;
    
    dragBtn.addEventListener("mousedown", (e) => {
      isDragging = true;
      
      // get previous translate values
      const [tranX, tranY] = (popup.style.translate || '0 0').split(' ').map(v => parseInt(v, 10));
      
      offsetX = e.clientX - tranX;
      offsetY = e.clientY - tranY;
    });
    
    document.addEventListener("mousemove", (e) => {
      if (!isDragging) return;
    
      popup.style.translate = `${e.clientX - offsetX}px ${e.clientY - offsetY}px`;
    });
    
    document.addEventListener("mouseup", (e) => {
      isDragging = false;
    });
    #popup {
      position: fixed;
      top: 20px;
      right: 20px;
      min-width: 350px;
      max-width: 500px;
      background: var(--dark-bg, #222);
      color: var(--dark-text, #fff);
      border: 1px solid #333;
      box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.4);
      padding: 15px;
      border-radius: 8px;
      z-index: 10000;
      transform-style: preserve-3d;
    }
    
    #popup-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    
    #popup-title {
      font-size: 14px;
      font-weight: bold;
    }
    
    button {
      border: none;
      cursor: pointer;
      border-radius: 4px;
      font-size: 16px;
      width: 26px;
      height: 26px;
      text-align: center;
      padding: 0;
    }
    
    #drag-btn {
      background: #326042;
      color: white;
      cursor: grab;
    }
    
    #theme-btn {
      background: #ef713b;
      color: white;
    }
    
    #close-btn {
      background: #ff5252;
      color: white;
    }
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Song Lyrics Finder</title>
      <link rel="stylesheet" href="src/style.css">
    </head>
    
    <body>
      <div id="popup">
        <div id="popup-header">
          <p id="popup-title">Song Lyrics Finder (from Genius.com)</p>
          <div style="display: flex; align-items: center; gap: 5px;">
            <button id="drag-btn">✥</button>
            <button id="theme-btn">&#9681;</button>
            <button id="close-btn">&#11199;</button>
          </div>
        </div>
      </div>
    </body>
    
    </html>

    Outra opção é redefinir righte autodefinir o leftevento atual ao pressionar o mouse, porque vamos atualizá-lo leftde agora em diante:

    const popup = document.getElementById("popup");
    const dragBtn = document.getElementById("drag-btn");
    
    let offsetX, offsetY, isDragging = false;
    
    dragBtn.addEventListener("mousedown", (e) => {
      isDragging = true;
      
      const { left } = popup.getBoundingClientRect();
      
      // set right to auto so it won't interfere
      popup.style.right = 'auto';
      
      // set left
      popup.style.left = `${left}px`;
    
      offsetX = e.clientX - popup.offsetLeft;
      offsetY = e.clientY - popup.offsetTop;
    });
    
    document.addEventListener("mousemove", (e) => {
      if (!isDragging) return;
      
      popup.style.left = `${e.clientX - offsetX}px`;
      popup.style.top = `${e.clientY - offsetY}px`;
    });
    
    document.addEventListener("mouseup", (e) => {
      isDragging = false;
    });
    #popup {
      position: fixed;
      top: 20px;
      right: 20px;
      min-width: 350px;
      max-width: 500px;
      background: var(--dark-bg, #222);
      color: var(--dark-text, #fff);
      border: 1px solid #333;
      box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.4);
      padding: 15px;
      border-radius: 8px;
      z-index: 10000;
    }
    
    #popup-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    
    #popup-title {
      font-size: 14px;
      font-weight: bold;
    }
    
    button {
      border: none;
      cursor: pointer;
      border-radius: 4px;
      font-size: 16px;
      width: 26px;
      height: 26px;
      text-align: center;
      padding: 0;
    }
    
    #drag-btn {
      background: #326042;
      color: white;
      cursor: grab;
    }
    
    #theme-btn {
      background: #ef713b;
      color: white;
    }
    
    #close-btn {
      background: #ff5252;
      color: white;
    }
    <div id="popup">
      <div id="popup-header">
        <p id="popup-title">Song Lyrics Finder (from Genius.com)</p>
        <div style="display: flex; align-items: center; gap: 5px;">
          <button id="drag-btn">✥</button>
          <button id="theme-btn">&#9681;</button>
          <button id="close-btn">&#11199;</button>
        </div>
      </div>
    </div>

    • 1

relate perguntas

  • classificação de mesclagem não está funcionando - código Javascript: não é possível encontrar o erro mesmo após a depuração

  • método select.remove() funciona estranho [fechado]

  • Sempre um 401 res em useOpenWeather () - react-open-weather lib [duplicado]

  • O elemento de entrada não possui atributo somente leitura, mas os campos ainda não podem ser editados [fechado]

  • Como editar o raio do primeiro nó de um RadialTree D3.js?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve