у меня есть перетаскиваемый элемент и т. д., но я хочу, чтобы его можно было перемещать только по заголовку, чтобы вы все равно могли выделять/щелкать объекты внутри div. я могу использовать только javascript :) я получил этот фрагмент кода от W3Schools, но я мало что знаю о редактировании/написании JavaScript :,D
Спасибо !! (ps, я разобрался с CSS, но в моем коде все перепутано, и я не могу удосужиться скопировать и вставить его, чтобы это имело смысл - но если это необходимо, я с радостью предоставлю!!)
dragElement(document.getElementById("elem"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
<div id = "elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style = "width: 185px;height: 117px; display:none; z-index:11">
<div class = "elemTitle">
play some music?
<button style = "text-align:right; float:right;" onClick = "closePopup()"> x </button>
</div>
<div id = "musicplayer">
<div>
<marquee scrollamount = "8" class = "songtitle"></marquee>
</div>
<table class = "controls">
<tr>
<td>
<div class = "prev-track" onclick = "prevTrack()"><i class = "fas fa-backward"></i></div>
</td>
<td>
<div class = "playpause-track" onclick = "playpauseTrack()" ><i class = "fas fa-play"></i></div>
</td>
<td>
<div class = "next-track" onclick = "nextTrack()"><i class = "fas fa-forward"></i></div>
</td>
</tr>
</table>
<div class = "seeking">
<div class = "current-time">00:00</div>
<input type = "range" min = "1" max = "100" value = "0" class = "seek_slider" onchange = "seekTo()">
<div class = "total-duration">0:00</div>
</div>
<audio id = "music" src = ""></audio>
</div>



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я не уверен, что именно нужно изменить, чтобы это заработало, но position: absolute необходимо на перетаскиваемом элементе (по крайней мере, после начала перетаскивания).
Теперь он также настроен так, что заголовок можно передавать как дескриптор и использовать для перемещения элемента div, а также добавлены условия, если элемент удаляется, когда позиция < 0 вверху или слева. Можно было бы использовать условия, чтобы правая и нижняя часть были > ширины или высоты, а обработчик событий для onmouseout для удаления перетаскиваемого элемента был бы неплохой идеей, поскольку в противном случае элемент удерживается.
Прослушиватели событий также следует удалять, когда они не нужны, а не просто обнулять их, поскольку это может вызвать утечку памяти, поскольку они все еще подключены и доступны для работающего кода.
Этот урок предназначен для перетаскиваемых элементов с возможностью изменения размера, но вы можете адаптировать его, чтобы сделать элемент просто перетаскиваемым. Наверняка есть и другие гиды. Настоятельно рекомендую MDN — сеть разработчиков Mozilla — документация подробная, а примеры, как правило, высокого качества и направлены на хорошее изучение частей более крупной вещи, а не просто на изучении основ, как это обычно делает W3Schools.
function closePopup() {
}
function dragElement(elmnt, handle) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (handle) { // True if handle is defined by the caller
/* if present, the header is where you move the DIV from:*/
handle.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
if (parseInt(elmnt.style.top) < 0) {
elmnt.style.top = 0;
}
if (parseInt(elmnt.style.left) < 0) {
elmnt.style.left = 0;
}
}
}
dragElement(document.getElementById("elem"),
document.querySelector(".elemTitle"));<div id = "elem" style = "width: 185px;height: 117px; z-index:11; position:absolute; user-select: none">
<div class = "elemTitle">
play some music?
<button style = "text-align:right; float:right;" onClick = "closePopup()"> x </button>
</div>
<div id = "musicplayer">
<div>
<marquee scrollamount = "8" class = "songtitle"></marquee>
</div>
<table class = "controls">
<tr>
<td>
<div class = "prev-track" onclick = "prevTrack()"><i class = "fas fa-backward"></i></div>
</td>
<td>
<div class = "playpause-track" onclick = "playpauseTrack()" ><i class = "fas fa-play"></i></div>
</td>
<td>
<div class = "next-track" onclick = "nextTrack()"><i class = "fas fa-forward"></i></div>
</td>
</tr>
</table>
<div class = "seeking">
<div class = "current-time">00:00</div>
<input type = "range" min = "1" max = "100" value = "0" class = "seek_slider" onchange = "seekTo()">
<div class = "total-duration">0:00</div>
</div>
<audio id = "music" src = ""></audio>
</div>Ох, лол; да - обновлено, чтобы соответствовать. Также исправлена ошибка, при которой пытался выбрать заголовок с идентификатором, но у него был только класс. СМХ. И добавил user-select: none, чтобы пользователи, нажимая и перетаскивая фон, не выделяли текст.
ЭЭЭ спасибо вам огромное!!! <3
например, я просто хочу, чтобы ЗАГОЛОВОК перемещал весь div, я не хочу, чтобы его можно было перетаскивать из любой другой точки div, кроме заголовка, если это имеет смысл? и спасибо за советы!! :D