Проблема с возможностью перетаскиваемого полукруга войти внутрь панели

Когда я изначально пытаюсь вытащить полукруг с конца влево, он входит в планку не так, как мне хочется, и появляется там. На самом деле у меня установлено значение minBarWidth равное 3, что соответствует ширине полосы, но это все равно не решило проблему.

// Make the handle draggable
dragElement(document.getElementById("handle"));

function dragElement(elmnt) {
  var startPosX = 0, currentPosX = 0;
  var maxBarWidth = window.innerWidth  - (elmnt.offsetWidth /16); // Tarayıcı penceresinin genişliğini kullan , Set the maximum width for the bar.

  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    startPosX = e.clientX;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  currentPosX = e.clientX - startPosX;
  startPosX = e.clientX;
  var bar = document.getElementById("bar");
  var newWidth = bar.offsetWidth + currentPosX;

  // Define the minimum width to keep the handle from entering the bar area
  var minBarWidth = 3; // This is the initial width of the bar

  // Define the maximum width as a percentage of the window's width
  var maxBarWidth = window.innerWidth- elmnt.offsetWidth / 16;

  // Restrict the width within the minimum and maximum bounds
  newWidth = Math.max(minBarWidth, Math.min(newWidth, maxBarWidth));

  // Set the new width
  bar.style.width = newWidth + "px";

  // If the new width is at the minimum, keep the handle from going into the bar
  if (newWidth <= minBarWidth) {
    elmnt.style.right = "0px"; // This keeps the handle from entering the bar area
  } else {
    elmnt.style.right = "-50px"; // This is for when the handle is not at the minimum width
  }
}

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#bar {
  position: fixed; /* Fixed position to stay in place on scroll */
  top: 0;
  bottom: 0;
  left: 0;
  width: 3px; /* Initial width of the bar */
  background-color: #f1f1f1; /* Background of the bar */
  border-right: 1px solid #d3d3d3; /* Border of the bar */
  z-index: 9;
}

#handle {
  width: 100px; /* Diameter of the handle circle */
  height: 100px; /* Height of the handle circle */
  background-color: #2196F3;
  border-radius: 50%; /* Make it round */
  position: absolute; /* Absolute position within the bar div */
  top: 50%; /* Center it vertically */
  right: -50px; /* Align to the right of the bar */
  transform: translateY(-50%); /* Adjust vertical position */
  cursor: pointer; /* Change cursor to indicate it's draggable */
  z-index: 10;
  clip-path: inset(0 0 0 50%); /* Clip left half of the circle */
}
<div id = "bar">
  <!-- This is the draggable handle -->
  <div id = "handle"></div>
</div>

Нежелательное состояние:

представление, которое должно быть действительным, даже если его принудительно переместить влево:

Что делает установка права на 0? Я ожидаю, что правая часть элемента будет установлена ​​справа от панели, что и происходит. И помните, что путь обрезки не меняет размеры элемента. Это чисто визуально.

A Haworth 08.04.2024 09:11

Это проблема JS, проблема CSS или проблема «бэкэнда» (что бы это ни значило)?

Nico Haase 08.04.2024 09:35
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
64
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

элемент менять не нужно elmnt.style.right. Подобно тому, как вы обрезаете элемент с помощью CSS, вы не меняете положение (клип просто визуален), он играет со свойством width, которое изменило местоположение элемента.

// Make the handle draggable
dragElement(document.getElementById("handle"));

function dragElement(elmnt) {
  var startPosX = 0, currentPosX = 0;
  var maxBarWidth = window.innerWidth  - (elmnt.offsetWidth /16); // Tarayıcı penceresinin genişliğini kullan , Set the maximum width for the bar.

  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    startPosX = e.clientX;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  currentPosX = e.clientX - startPosX;
  startPosX = e.clientX;
  var bar = document.getElementById("bar");
  var newWidth = bar.offsetWidth + currentPosX;

  // Define the minimum width to keep the handle from entering the bar area
  var minBarWidth = 3; // This is the initial width of the bar

  // Define the maximum width as a percentage of the window's width
  var maxBarWidth = window.innerWidth- elmnt.offsetWidth / 16;

  // Restrict the width within the minimum and maximum bounds
  newWidth = Math.max(minBarWidth, Math.min(newWidth, maxBarWidth));

  // Set the new width
  bar.style.width = newWidth + "px";
}

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#bar {
  position: fixed; /* Fixed position to stay in place on scroll */
  top: 0;
  bottom: 0;
  left: 0;
  width: 3px; /* Initial width of the bar */
  background-color: #f1f1f1; /* Background of the bar */
  border-right: 1px solid #d3d3d3; /* Border of the bar */
  z-index: 9;


  
}

#handle {
  width: 100px; /* Diameter of the handle circle */
  height: 100px; /* Height of the handle circle */
  background-color: #2196F3;
  border-radius: 50%; /* Make it round */
  position: absolute; /* Absolute position within the bar div */
  top: 50%; /* Center it vertically */
  right: -50px; /* Align to the right of the bar */
  transform: translateY(-50%); /* Adjust vertical position */
  cursor: pointer; /* Change cursor to indicate it's draggable */
  z-index: 10;
  clip-path: inset(0 0 0 50%); /* Clip left half of the circle */
}
<div id = "bar">
  <!-- This is the draggable handle -->
  <div id = "handle"></div>
</div>

Почему ты еще и бару поставил right: -50px? Я думаю, что это отменяется width на следующей строке.

DustInComp 08.04.2024 09:54

да, вы правы, собственность бесполезна. Я редактирую свой ответ с помощью этого элемента

jeremy-denis 08.04.2024 10:04

Другие вопросы по теме