问题
I want to achieve an horizontal click and dragg website, it works perfectly in Chrome but not in Firefox.
My problem : Click and dragg on links in Firefox is making the stop-icon appears next to the cursor and then blocking mouseup event.
What I know : The problem is only appearing on links and I found this post (javascript and dragging in firefox) that is suggesting to use addEventListener on the document, but it didn't fix it.
Old code below (to see the updated one go on codepen)
const slider = document.querySelector('.items');
let isDown = false;
let startX;
let scrollLeft;
document.addEventListener('mousedown', (e) => {
isDown = true;
slider.classList.add('active');
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
});
document.addEventListener('mouseleave', () => {
isDown = false;
slider.classList.remove('active');
});
document.addEventListener('mouseup', () => {
isDown = false;
slider.classList.remove('active');
});
document.addEventListener('mousemove', (e) => {
if(!isDown) return;
e.preventDefault();
const x = e.pageX - slider.offsetLeft;
const walk = (x - startX) * 3; //scroll-fast
slider.scrollLeft = scrollLeft - walk;
console.log(walk);
});
HTML
<div class="grid-container">
<main class="grid-item main">
<div class="items">
<a class="item item1" href="#"></a>
<a class="item item2" href="#"></a>
<a class="item item3"></a>
<a class="item item4"></a>
<div class="item item5"></div>
<div class="item item6"></div>
<div class="item item7"></div>
<div class="item item8"></div>
<div class="item item9"></div>
<div class="item item10"></div>
</div>
<p>Click & Drag <i>powered by Javascript</i></p>
</main>
</div>
回答1:
SOLUTION : To fix the problem you can do
const links = document.querySelectorAll('a');
links.forEach(element => {element.addEventListener('mousedown',function(e) {
e.preventDefault();
})
})
Here is the link :https://codepen.io/greg_o/pen/jQrMON
来源:https://stackoverflow.com/questions/53227879/click-and-drag-on-links-in-firefox-are-blocking-mouseup-events