Home  >  Article  >  Web Front-end  >  How to perfectly solve the mousemove event bug under Chrome in jQuery?

How to perfectly solve the mousemove event bug under Chrome in jQuery?

黄舟
黄舟Original
2017-06-28 10:41:042921browse

There is a bug about mousemove under Chrome:
1. When the mouseup event is triggered, including when click and contextmenu are triggered, the mousemove event will also be triggered;
2. What’s even weirder is that when you continuously trigger contextmenu events, the mousedown event will be replaced by mousemove.
A solution I’m currently thinking of is to compare by timestamp:

var body = document.querySelector("h1");
var timeStamp;

body.addEventListener("mousedown", function (e) {
    console.log("mouse down");
}, false);

body.addEventListener("mouseup", function (e) {
    console.log("mouse up");
    timeStamp = e.timeStamp;
})

body.addEventListener("mousemove", function (e) {
    if (!timeStamp || ( e.timeStamp - timeStamp > 10)) {
        console.log("mouse move");    
    }
})

This can avoid triggering the click event, or triggering the mousemove caused by the left mouse button mouseup. However, the mousemove caused by the contextmenu described above still cannot be solved well.

Is there any perfect solution? Or we can only avoid this situation as much as possible

<input type="text" id="a1" />

$("#a1").mousemove(function(){
	if ($(this).data("x") === event.pageX && $(this).data("y") === event.pageY) {
		return false;
	}
	$(this).data({"x":event.pageX, "y":event.pageY});
	$(this).after("1");
})

The purpose of using jq is to use .data() in all browsers. This is the way of thinking, you can change it yourself.

Also, after an element is bound to mousemove, do not bind other events.

Finally: Try not to use mousemove, it consumes too many resources.

You can confirm whether it is a move operation by comparing the position of mousedown

document.onmousemove = function(e) {  
// 不是move操作  if (x === mouseDown.x && y === mouseDown.y) {
        return false;
    }};
document.onmousedown = function (e) {  
mouseDown = { x: e.clientX, y: e.clientY };};


The above is the detailed content of How to perfectly solve the mousemove event bug under Chrome in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn