[英]How to disable the onclick event of a draggable button?
I have a draggable div, inside it is a button, this button will popup a modal on clicked.我有一个可拖动的 div,里面有一个按钮,这个按钮会在点击时弹出一个模式。 But whenever i click on that div in order to drag it, it triggers the onclick event of the button as well.
但是每当我点击那个 div 来拖动它时,它也会触发按钮的 onclick 事件。 I want to disable that button if i were dragging, it should only be trigger when i simply click on it.
如果我正在拖动,我想禁用该按钮,它应该只在我简单地点击它时触发。
dragElement(document.getElementById("fdivAdd")); 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; } }
#fdivAdd { width: 80px; height: 80px; position: fixed; right: 45px; bottom: 93px; cursor: pointer; z-index: 9; background-color: #007bff; border-radius: 40px; } #fbtnAdd { width: 80px; height: 80px; border-radius: 40px; /* margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translateY(-50%) translateX(-50%); transform: translateY(-50%) translateX(-50%); */ font-size: 25px; color: white; }
<div id="fdivAdd"> <p id="fbtnAdd" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Add</p> </div>
Use a boolean and make life easy:使用 boolean 让生活更轻松:
var moving = false;
if(moving == true) {
disableBtn("Button Id");
} else {
// Do what you did before
}
function disbaleBtn(btnId) {
console.log(btnId);
document.getElementById(btnId).onclick = "return false";
}
Set the bool to true in your dragging code, and false while not.在拖动代码中将 bool 设置为 true,否则设置为 false。 Add the if statement to where the onclick is otherwise used
将 if 语句添加到 onclick 否则使用的位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.