在鼠标悬停时添加事件,如何只添加一次事件
Adding events on mouseover, how do you add an event only once?
我有一个事件侦听器,它的工作原理是这样的(伪代码):
canvas.onmousemove = function (e) { checkCollision(e); };
var checkCollision = function(e){
var context = canvas.getContext('2d');
var coordinates = getMouseXY();
// draw any shape with the context
if(context.isPointInPath(coordinates.X, coordinates.Y){
$(canvas).on('click', alertFunction, e);
return; //stop the function from doing anything else
}
$(canvas).off('click', alertFunction, e);
};
var alertFunction = function(e){
alert("this alert should only show once per click");
};
我的预期结果:当我将鼠标悬停在画布中绘制的特定线条上时,我可以单击以获取警报。
实际结果:当我在画布中单击我的行时,我收到很多警报。我的猜测:对于我在元素上移动的每个像素,都会添加点击侦听器。因此,如果我将鼠标悬停在元素上,警报会播放很多次。如果我将鼠标悬停在元素外部,则对于我在元素外移动的每个像素,将删除一个事件侦听器。
有没有更好的方法可以做到这一点?
如果你这样改变呢?
canvas.onmousemove = function (e) { checkCollision(e); };
var checkCollision = function(e){
var context = canvas.getContext('2d');
var coordinates = getMouseXY();
// draw any shape with the context
if(context.isPointInPath(coordinates.X, coordinates.Y){
$(canvas).off().on('click', alertFunction, e);
return; //stop the function from doing anything else
}
};
var alertFunction = function(e){
alert("this alert should only show once per click");
};
您可以使用
hover()
函数:
$('div').hover(function() {
alert('hoverd');
}, function() {
alert('out of div');
});
div {
padding: 30px;
border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>hover</div>
jQuery 有一个方法,它只允许你将事件附加到事件处理程序一次。http://api.jquery.com/one/
$( "#foo" ).one( "mouseover", function() {
checkCollision();
});
从您的描述来看,您最好删除 onmousemove 并将所有代码放在单击中。
在 onclick 中添加 if isPointInPath 函数,如果为 true,则发出警报功能,否则不执行任何操作。
$(canvas).click(function() {
var context = canvas.getContext('2d');
var coordinates = getMouseXY();
if(context.isPointInPath(coordinates.X, coordinates.Y){
alertFunction(e);
return; //stop the function from doing anything else
}
})
每次鼠标在画布上移动 1 个像素时,都会触发 Onmouseover,因此它不适合绑定另一个函数。
如果您绝对必须这样做,请检查您的元素上是否已经存在绑定
$.data(!$(canvas).get(0), 'events' ).click) {
$(canvas).on('click',alertfucntion, e}
}
或类似的东西...
另一个带有 .off() 的评论可能有效; 我可能弄错了; 但我认为它删除了所有绑定,然后为您移动的每个像素重新绑定 click(),这可能会导致以后出现很多性能问题,也许?
相关文章:
- 如何在for循环中添加事件侦听器
- 如果选中了多个复选框,如何添加事件
- 正在ng重复元素上添加事件
- 在动态创建的标记上添加事件
- 如何在HTML列表中添加事件's子弹
- 将事件侦听器添加到文档,而不是签入元素存在,然后添加事件侦听器
- jQuery完整日历添加事件,仅包含月份和日期
- 是否可以在数字输入框中的小按钮中添加事件侦听器
- 在Google Chrome扩展中添加事件侦听器
- AngularJS:在.post()之后添加事件侦听器
- 对象 Javascript 中的标签无效 - 想要添加事件列表器
- 添加事件侦听器不起作用
- 如何为angular js条形图添加事件
- 在 http 请求中添加事件侦听器 ( request.on ) 是什么意思?而笏就是它的用途
- Iron:路由器在更改路由器上添加事件
- 如何为表行结果的每个按钮添加事件侦听器
- 在 javascript 中添加事件处理程序的位置
- YouTube API-动态添加事件侦听器
- 在聚合物的子菜单标题中添加事件
- 检查是否可以添加事件侦听器而不添加