如何在mouseDown按下js时实现mousemove

how to implement mousemove while mouseDown pressed js

我必须只在按下鼠标时实现鼠标移动事件。

我只需要在鼠标按下和移动时执行"OK Moved"。

我使用了这个代码

 $(".floor").mousedown(function() {
  $(".floor").bind('mouseover',function(){
      alert("OK Moved!");
  });
})
.mouseup(function() {
 $(".floor").unbind('mouseover');
});

使用 mousemove 事件。

来自 mousemove and mouseover jquery 文档:

The mousemove event is sent to an element when the mouse pointer moves inside the element.

The mouseover event is sent to an element when the mouse pointer enters the element.

示例:(检查控制台输出)

$(".floor").mousedown(function () {
    $(this).mousemove(function () {
        console.log("OK Moved!");
    });
}).mouseup(function () {
    $(this).unbind('mousemove');
}).mouseout(function () {
    $(this).unbind('mousemove');
});

https://jsfiddle.net/n4820hsh/

在纯 javascript 中,您可以通过

实现
function mouseMoveWhilstDown(target, whileMove) {
    var endMove = function () {
        window.removeEventListener('mousemove', whileMove);
        window.removeEventListener('mouseup', endMove);
    };

    target.addEventListener('mousedown', function (event) {
        event.stopPropagation(); // remove if you do want it to propagate ..
        window.addEventListener('mousemove', whileMove);
        window.addEventListener('mouseup', endMove);   
    });
}

然后使用

中的函数
mouseMoveWhilstDown(
    document.getElementById('move'),
    function (event) { console.log(event); }
);

(注意:在上面的示例中,您不需要该函数 - 您可以将其称为 mouseMoveWhilstDown(document.getElementById('move'), console.log),但除了将其输出到控制台之外,您可能还想用它做一些事情!)

默认行为将从 运行 开始停止 mouseMove 和 mouseUp,您基本上可以通过将 event.preventDefault() 添加到 mousedown 函数

来解决此问题

请确保您使用在 mousedown 函数中传递的相同参数名称来触发 preventDefault(),否则它将不起作用,在下面的示例中,我将事件作为参数传递给 mousedown 函数,然后触发 preventDefault () 输入 event.preventDefault()

let sliderImages =  Array.from(document.getElementsByClassName('slidess'));
const sliderPos = sliderImages.forEach( function (slide, index) {

    let mousePosStart, isDown = false;

    slide.addEventListener('mousedown', mousedown)
    slide.addEventListener('mousemove', mousemove)
    slide.addEventListener('mouseup', mouseup)

function mousedown(event) {
    if (isDown == false) {
        mousePosStart = event.pageX - this.offsetLeft;
        isDown = true;
        event.preventDefault();
    }
}

function mousemove(event) {
    if (isDown == true) {
        let mousePosMove = event.pageX - this.offsetLeft;
    }
}

function mouseup(event) {
    if (isDown === true) {
        isDown = false;
        let mousePosEnd = event.pageX - this.offsetLeft;
    }
}     

});