gpt4 book ai didi

javascript - 根据当前鼠标移动位置仅触发一次事件

转载 作者:行者123 更新时间:2023-11-29 21:04:45 26 4
gpt4 key购买 nike

如何在下面代码段中显示的每种条件/情况下仅触发一次事件?

在我的示例中,如果鼠标位置的 x 位置值在 25 - 50 之间,如果 y 位置值为 0 - 25,它将触发一个事件。但如果您看到控制台,该事件会重复触发。

如何在每个条件下仅记录一次控制台(或更多事件,如果稍后添加)?如果鼠标离开“条件”并稍后返回,console.log 会再次触发吗?

$(document).mousemove(function(getCurrentPos){
var xCord = getCurrentPos.pageX;
var yCord = getCurrentPos.pageY;
xPercent = xCord / $( document ).width() * 100;
yPercent = yCord / $( document ).height() * 100;


if ((xPercent > 0 && xPercent < 25) && (yPercent >= 0 && yPercent < 25)){
console.log('1'); /* how to fire only once?*/
/* more events here later */
} else if ((xPercent >= 25 && xPercent <= 50) && (yPercent > 0 && yPercent < 25)) {


console.log('2'); /* how to fire only once?*/
/* more events here later */

}else if ((xPercent >= 50 && xPercent <= 75) && (yPercent > 0 && yPercent < 25)) {
console.log('3');/* how to fire only once?*/
/* more events here later */
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

最佳答案

给你!您只需要避免为每个条件设置一些唯一值并在输入时再次检查...并在不输入时重新设置。

var currentArea = false;
$(document).mousemove(function(getCurrentPos){
var xCord = getCurrentPos.pageX;
var yCord = getCurrentPos.pageY;
xPercent = xCord / $( document ).width() * 100;
yPercent = yCord / $( document ).height() * 100;

if ((xPercent > 0 && xPercent < 25) && (yPercent <= 0 && yPercent < 25)){
if(currentArea!="Area1"){
console.log('1');
currentArea = "Area1";
}
} else if ((xPercent >= 25 && xPercent <= 50) && (yPercent > 0 && yPercent < 25)) {
if(currentArea!="Area2"){
console.log('2');
currentArea = "Area2";
//do this
}
}else if ((xPercent >= 50 && xPercent <= 75) && (yPercent > 0 && yPercent < 25)) {
if(currentArea!="Area3"){
console.log('3');
currentArea = "Area3";
//do this
}
}else{
console.log('outside')
currentArea=false
}

});

关于javascript - 根据当前鼠标移动位置仅触发一次事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44558223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com