1 回答
TA贡献1829条经验 获得超7个赞
我可以建议的一种方法。
定义一个函数 preventClick
const preventClick = (e) => {
e.preventDefault();
e.stopImmediatePropagation();
}
定义一个变量isDragged以有条件地添加和删除事件侦听器。
let isDragged = false;
在mouseup事件中,您输入 2 种情况,isDragged = false(单击时)或isDragged = true(拖动时)
第一种情况: 移除阻止点击传播的事件监听器
第二种情况: 添加防止点击传播的事件监听器。
试试下面的代码,让我知道这是否有帮助。请注意,这不是优化代码。我正在为所有锚标记添加和删除事件处理程序,只是为了演示您可以遵循的方法。
const slider = document.querySelector(".wrapper");
const preventClick = (e) => {
e.preventDefault();
e.stopImmediatePropagation();
}
let isDown = false;
var isDragged = false;
let startX;
let scrollLeft;
slider.addEventListener("mousedown", e => {
isDown = true;
slider.classList.add("active");
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
});
slider.addEventListener("mouseleave", () => {
isDown = false;
slider.classList.remove("active");
});
slider.addEventListener("mouseup", e => {
isDown = false;
const elements = document.getElementsByClassName("book");
if(isDragged){
for(let i = 0; i<elements.length; i++){
elements[i].addEventListener("click", preventClick);
}
}else{
for(let i = 0; i<elements.length; i++){
elements[i].removeEventListener("click", preventClick);
}
}
slider.classList.remove("active");
isDragged = false;
});
slider.addEventListener("mousemove", e => {
if (!isDown) return;
isDragged = true;
e.preventDefault();
const x = e.pageX - slider.offsetLeft;
const walk = (x - startX) * 2;
slider.scrollLeft = scrollLeft - walk;
});
document.getElementsByClassName("book").ondragstart = function() {
console.log("Drag start");
};
.wrapper {
position: relative;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
overflow: auto;
min-width: 100%;
}
.book {
width: auto;
height: 100vh;
min-width: 50vw;
}
.one {
background-color: #d07fe0;
}
.two {
background-color: #808888;
}
.three {
background-color: #83e7dc;
}
.four {
background-color: #edf7a8;
}
.five {
background-color: #e9d98f;
}
.six {
background-color: #fdd;
}
<body>
<div class="wrapper">
<a href="https://stackoverflow.com/" class="book one"></a>
<a href="https://stackoverflow.com/" class="book two"></a>
<a href="https://stackoverflow.com/" class="book three"></a>
<a href="https://stackoverflow.com/" class="book four"></a>
<a href="https://stackoverflow.com/" class="book five"></a>
<a href="https://stackoverflow.com/" class="book six"></a>
</div>
</body>
添加回答
举报