我正在尝试在拖动时阻止点击事件。我认为最简单的版本就是用户按下、移动再释放鼠标时,我不希望触发点击事件。这是脚本:
const tabsBox = document.querySelector('.kemem'),
allTabs = tabsBox.querySelectorAll('.pop-post'),
arrowIcons = document.querySelectorAll('.icon-mem svg')
let isDragging = false
const handleIcons = scrollVal => {
let maxScrollableWidth = tabsBox.scrollWidth - tabsBox.clientWidth
arrowIcons[0].parentElement.style.display = scrollVal <= 0 ? 'none' : 'flex'
arrowIcons[1].parentElement.style.display =
maxScrollableWidth - scrollVal <= 1 ? 'none' : 'flex'
}
arrowIcons.forEach(icon => {
icon.addEventListener('click', () => {
// 如果点击的图标是左侧的,从 tabsBox 的 scrollLeft 中减去 350,否则加上
let scrollWidth = (tabsBox.scrollLeft += icon.id === 'left' ? -340 : 340)
handleIcons(scrollWidth)
})
})
allTabs.forEach(tab => {
tab.addEventListener('click', () => {
e.preventDefault();
e.stopPropagation();
tabsBox.querySelector('.active').classList.remove('active')
tab.classList.add('active')
})
})
const dragging = e => {
e.preventDefault();
e.stopPropagation();
if (!isDragging) return
tabsBox.classList.add('dragging')
tabsBox.scrollLeft -= e.movementX
handleIcons(tabsBox.scrollLeft)
}
const dragStop = () => {
isDragging = false
e.preventDefault();
e.stopPropagation();
tabsBox.classList.remove('dragging')
}
tabsBox.addEventListener('mousedown', () => (isDragging = true))
tabsBox.addEventListener('mousemove', dragging)
document.addEventListener('mouseup', dragStop)
<div class='icon-mem lefto'><div class='overflow-left'></div><svg aria-hidden='true' class='jt-icon' id='left'><use xlink:href='#i-arrow-l'></use></svg></div>
<ul class="kemem">
<li class="pop-list">Programming</li>
<li class="pop-list">HTML</li>
<li class="pop-list">CSS</li>
<li class="pop-list">Python</li>
</ul>
<div class='icon-mem righto'><div class='overflow-right'></div><svg aria-hidden='true' class='jt-icon' id='right'><use xlink:href='#i-arrow-r'></use></svg></div>
这是演示链接:demo
我是否遗漏了更简单的解决方案?