我熟悉jQuery并制作一个小应用程序,其中红色框在屏幕上移动,用户必须尝试点击它,当用户alert()
弹出一个框时,问题是alert()
即使在'好的'被压了.我可以阻止它的唯一方法是反复点击'ok'并最终消失.
以下是显示警告框的代码:
function Animate() {
var _newPosition = GetNewPosition();
// Sets new position of div
div.animate({
top: _newPosition[0],
left: _newPosition[1]
}, function () {
div.on('click', function () {
alert('You clicked the box!');
});
Animate();
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的JSFiddle再现问题
我原本以为我可以通过false
在调用alert()
例如之后返回来解决它:
div.on('click', function () {
alert('You clicked the box!');
return false;
});
Run Code Online (Sandbox Code Playgroud)
但这也不起作用.
我知道这应该是一个简单的事情,但我似乎无法得到我的拇指.
在动画完成回调中递归调用click处理程序,该回调将click
多次绑定元素上的事件.因此,当单击该元素时,将多次调用该处理程序.
要解决此问题,请仅绑定事件一次.
function Animate() {
var _newPosition = GetNewPosition();
// Sets new position of div
div.animate({
top: _newPosition[0],
left: _newPosition[1]
}, Animate);
}
Run Code Online (Sandbox Code Playgroud)
而在准备()
$(document).ready(function () {
Animate();
div.on('click', function() {
// Code here
alert('clicked');
});
});
Run Code Online (Sandbox Code Playgroud)
使用Animate
动画的完整回调作为参考
function() {
Animate();
}
Run Code Online (Sandbox Code Playgroud)
函数引用将传递给animate
它,并在动画完成时调用它.
建议:
mousedown
事件跟踪移动对象上的单击animate
.var div = $('#box');
$(document).ready(function() {
Animate();
div.on('mousedown', function() {
// Code here
console.log('clicked');
});
});
function GetNewPosition() {
// Get dimentions of the window and remove the div area
var h = $(window).height() - 50;
var w = $(window).width() - 50;
// New height and width is auto generated
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function Animate() {
var _newPosition = GetNewPosition();
// Sets new position of div
div.animate({
top: _newPosition[0],
left: _newPosition[1]
}, (Math.floor(Math.random() * 5000) + 1), Animate);
}
Run Code Online (Sandbox Code Playgroud)
#box {
width: 50px;
height: 50px;
background-color: red;
position: fixed;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id="success"></h3>
<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)