如何跟踪元素移动和特定位置的触发功能

How to track element movement and trigger function at specific spot?

本文关键字:位置 定位 功能 移动 何跟踪 跟踪 元素      更新时间:2023-09-26

我有一个 #ball,当点击时,使用jquery animate使用以下代码向下移动210px:

 $('#ball').click(function() {
    $(this).animate({
        top: '+=210px'
    }, 500);
    setTimeout(crack, 400);
});​

目前我使用超时来触发下一个函数,即"破解"。相反,我想跟踪 #ball 的移动,当它的 css top = 210px 时,我想触发函数 crack(),我该怎么做?

我在一篇有点类似的帖子中看到,Step 函数可能是我正在寻找的,但我不确定如何根据 http://api.jquery.com/animate/提供的信息处理该解决方案

查看演示:http://jsfiddle.net/EnigmaMaster/hbvev/4/

如果您知道球会在210px到达禁区,我不确定为什么要使用追踪器。

如果你想摆脱 setTimeout,那么使用 .animate 回调函数,当球到达盒子时将调用该函数。

$('#ball').click(function() {
    $(this).animate({
        top: '+=210px'
    }, 500, crack); //<== crack will be called after ball animation
});​

演示

如果您想在球接触盒子时调用破解并且仍然继续盒子的移动,那么您可以执行它 2 步,如下所示,

$('#ball').click(function() {
    $(this).animate({
        top: '+=180px'
    }, 400, function() {
        crack();
        $(this).animate({
            top: '+=30px'
        }, 100);            
    });
});

另请查看此版本以慢动作 http://jsfiddle.net/skram/hbvev/8/获得乐趣

如果你真的想根据球的位置做点什么,那么是的,step可能是最好的方法:

$('#ball').click(function() {
    $(this).animate({
        top: '+=210px'
    }, {
        duration: 500,
        step: function() {
            if($(this).offset().top > 208) {
                 crack();
            }                
        }
    });
});

演示:http://jsfiddle.net/qJjnN/1/

现在,有几个警告:

  1. 可能会有性能影响。
  2. 每一步的位置不一定是整数,对象也不会存在于开始和停止位置之间的每个像素处。
  3. step不会在最终位置上调用,因此您实际上无法检查它是否是最终位置210

记住这些,您将无法检查 210px 的确切位置。 相反,您需要观察它何时经过某个位置,并且仅在该点触发crack,而不是之后的每个点:

$('#ball').click(function() {
    var cracked = false;
    $(this).animate({
        top: '+=210px'
    }, {
        duration: 500,
        step: function() {
            if($(this).offset().top > 208 && !cracked) {
                 cracked = true;
                 crack();
            }                
        }
    });
});

演示:http://jsfiddle.net/qJjnN/2/

step函数还具有参数nowfx,可用于查看正在动画的 css 的当前值。 对于要进行动画处理的每个 css 属性的每个步骤,都会调用step。 因此,您必须小心使用这些属性,因为您需要查看fx以查看您正在查看的属性值(如果您要对多个属性值进行动画处理,即 topleft)。

$('#ball').click(function() {
    var cracked = false;
    $(this).animate({
        top: '+=210px'
    }, {
        duration: 500,
        step: function(now, fx) {
            if(fx.prop != 'top') {
                 return;
            }
            if(now > 208 && !cracked) {
                 cracked = true;
                 crack();
            }                
        }
    });
});