简体   繁体   English

添加一个Javascript侦听器,该侦听器在元素具有某个Y位置时触发

[英]Adding a Javascript listener that triggers when an element has a certain Y position

Is there a way to add a listener that triggers a function when an element is at a certain y-position? 有没有一种方法可以添加当元素位于某个y位置时触发函数的侦听器?

On click, I have an element animating up with jQuery. 在单击时,我有一个使jQuery动起来的元素。

During that animation, the elements y-position will reach 0 (and go past it). 在该动画期间,元素y位置将达到0(并超过该位置)。 When it reaches 0, I'd like to trigger another function that displays a different . 当它达到0时,我想触发另一个显示不同的功能。

I've been trying to read about event management with anonymous event handling but have been unable to figure out how to get it working. 我一直在尝试阅读有关使用匿名事件处理的事件管理的信息,但一直无法弄清楚如何使其正常工作。 Thank you! 谢谢!

if your animation was from say 50 to -10, you could split it up into 2 animations. 如果您的动画从50到-10,则可以将其分成2个动画。 50 to 0, and 0 to -10. 50至0,以及0至-10。 That would give you the opportunity to call your function when the first animation completes, and wouldn't have the overhead of checking position on each step. 这将使您有机会在第一个动画完成时调用函数,而不会在每个步骤上检查位置。

You can use step option of animate method which is fired at each step of the animation. 您可以使用动画方法的step选项,该方法在动画的每个步骤均会触发。 Here you can check for the y-position of the element and trigger the required event. 在这里,您可以检查元素的y位置并触发所需的事件。

$(element).animate({
  height: '50%'
},
{
  step: function(now, fx) {
     //Here check the y-position of the element and then call the required function
     if($(fx.elem).offset().top == 0){
        //Code here
     }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM