如何防止点击并拖动

时间:2018-10-15 21:36:28

标签: javascript event-handling mouseup

我有水平图像,并且按住鼠标和拖动功能可以查看它,但这是每个图像都包裹在标签内的问题,所以当我按住并释放鼠标并且单击标签起作用时,我无法使用希望它能正常工作。

我要防止鼠标单击以使标签单击起作用,以便我可以正常按住并拖动

 <main>
        <div class="projects-list">
            <article class="old-and-blue fade-in">
                <h1>old and blue</h1>
                <figure>
                    <a href="projects/old-and-blue.html">
                        <img src="assets/media/images/slides/old-and-blue.jpg" alt="">
                    </a>
                </figure>
            </article>
            <article class="paperland fade-in">
                <h1>Paperland</h1>
                <figure>
                    <a href="projects/paperland.html">
                        <img src="assets/media/images/slides/paperland.jpg" alt="">
                    </a>
                </figure>
            </article>
            <article class="contessa fade-in">
                <h1>Contessa</h1>
                <figure>
                    <a href="projects/contessa.html">
                        <img src="assets/media/images/slides/contessa.jpg" alt="">
                    </a>
                </figure>
            </article>
            <article class="myself-and-i fade-in">
                <h1>Myself and I</h1>
                <figure>
                    <a href="projects/myself-and-i.html">
                        <img src="assets/media/images/slides/myself-and-i.jpg" alt="">
                    </a>
                </figure>
            </article>
        </div>
    </main>

这是我的js

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.style.transition = '1s';
});

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 个答案:

没有答案