I want to get MouseEvent
while I press down middle mouse button on a div
and drag the cursor out of the div
.
The problem is that when my web page is scrollable, I get scroll icon as soon as I press down middle mouse button, which I don't want.
I know calling preventDefault()
keeps the autoscrolling from being called but it also breaks my getting MouseEvent
if my web page is in iframe
.
I made a simple code snippet you can try and understand the issue.
Steps;
- Run code snippet
- Move mouse cursor over yellow
div
- Press down middle mouse button
At this point, you notice scroll is triggered.
- Still holding middle button down, move cursor out of the yellow
div
and iframe
Notice text in yellow div
is still updated.
Click anywhere to disable scroll.
Check 'Call preventDefault' checkbox and re-run steps from #2 to #4.
Notice text in yellow div
is NOT updated anymore.
As you can see, preventDefault
disables the autoscrolling but breaks the MouseEvent
.
var captured = false;
const myDiv = document.querySelector("#myDiv");
const releaseMouse = function() {
document.removeEventListener('mousemove', myHandler);
document.removeEventListener('mouseup', myHandler);
myDiv.addEventListener('mousemove', myHandler);
myDiv.addEventListener('mouseup', myHandler);
captured = false;
};
const captureMouse = function() {
myDiv.removeEventListener('mousemove', myHandler);
myDiv.removeEventListener('mouseup', myHandler);
document.addEventListener('mousemove', myHandler);
document.addEventListener('mouseup', myHandler);
captured = true;
};
const myHandler = function(ev) {
const message = `${ev.type} (${ev.clientX},${ev.clientY}) ${ev.currentTarget.tagName || "Document"}`;
switch (ev.type) {
case 'mousedown':
if (ev.buttons == 4) {
captureMouse();
myDiv.innerHTML = message;
if (document.querySelector("#checkbox1").checked) {
ev.preventDefault();
}
}
break;
case 'mousemove':
if (captured) {
myDiv.innerHTML = message;
}
break;
case 'mouseup':
releaseMouse();
myDiv.innerHTML = message;
break;
}
};
myDiv.addEventListener('mousedown', myHandler);
<div style="height: 2000px;">
<div id="myDiv" style="width: 500px; height: 150px; background-color: yellow;"></div>
<input type="checkbox" id="checkbox1" name="checkbox1">
<label for="checkbox1">Call preventDefault</label>
</div>
question from:
https://stackoverflow.com/questions/65924910/is-it-possible-to-disable-autoscrolling-when-middle-mouse-button-is-down-in-chro 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…