如何防止锚标记单击保持并拖动?就像当我握住鼠标并向左和向右拖动确定时一样,但是如果我从鼠标上移开手,将会发生单击,我试图在鼠标向上使用“阻止默认值”,但是它没有用
<a>
<img src=""/>
</a>
这是我的JavaScript
const projectList = document.querySelector('.projects-list');
let isDown = false;
let startX;
let scrollLeft;
projectList.addEventListener('mousedown', (e)=>{
isDown = true;
projectList.classList.add('active');
startX = e.pageX - projectList.offsetLeft;
scrollLeft = projectList.scrollLeft;
projectList.classList.add('active');
e.preventDefault();
});
projectList.addEventListener('mouseleave', ()=>{
isDown = false;
projectList.classList.remove('active');
});
projectList.addEventListener('mouseup', ()=>{
isDown = false;
projectList.classList.remove('active');
});
projectList.addEventListener('mousemove', (e)=>{
if ( !isDown ) return; // stop the function from running
e.preventDefault();
const x = e.pageX - projectList.offsetLeft;
const walk = x - startX;
projectList.scrollLeft = scrollLeft - walk;
});
答案 0 :(得分:0)
您需要将属性class="projects-list"
放在锚标记中
给定的html示例在任何地方都没有带有.projects-list
的元素
也querySelector
仅找到第一个匹配元素
替代:querySelectorAll
答案 1 :(得分:0)
在event.preventDefault
上使用<a>
,如下所示:
var canClick = false;
$("#NoClick").click(function() {
if (!canClick) {
event.preventDefault();
}
});
$("#Click").click(function() {
if (canClick) {
event.preventDefault();
}
});
$("button").click(function() {
canClick = !canClick;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Swap</button>
<br>
<a href="www.google.com" id="Click">This will work</a>
<br>
<a href="www.google.com" id="NoClick">This won't work</a>
除了可以更改mousedown
和mouseup
函数中的canClick以避免出现问题之外,