当元素到达屏幕上的某个位置时触发事件

trigger an event when an element reaches a position on the screen

本文关键字:位置 事件 元素 屏幕      更新时间:2023-09-26

我想根据元素的位置触发一些函数。此元素的位置每隔十分之一秒发生变化。有二十个函数需要触发。

我想到了这个伪代码:

When element position changes{
  Loop through all the coordinates to see if a function can be triggered{
     if the current element position matches the function's triggering position 
         execute the function
     }
}

但每隔几秒钟循环浏览所有可能的位置会给浏览器带来负担。因此,如果有办法举办活动的话。

有可能吗?

编辑:在甜菜根甜菜根评论之后,我必须说,移动的元素只在X横坐标上移动:所以只有一个维度。

这很像一个从左向右移动的水平时间线,当某一年到来时,一些动画就会发生。但是,移动速度可以由用户增加,因此不能选择固定时间触发动画。

必须有多种方法来实现您想要的。下面的代码利用jQuery处理自定义事件的能力来提供一个"松散耦合"的观察者模式。

$(function() {
    //Establish the two dozen functions that will be called.
    var functionList = [
        function() {...},
        function() {...},
        function() {...},
        ...
    ];
    var gridParams = {offset:10, pitch:65};//Example grid parameters. Adjust as necessary.
    //Establish a custom event and its handler.
    var $myElement = $("#myID").data('lastIndex', -1).on('hasMoved', function() {
        $element = $(this);
        var pos = $element.position();//Position of the moved element relative to its offset parent.
        var index = Math.floor((pos.left - gridParams.offset) / gridParams.pitch);//Example algorithm for converting pos.left to grid index.
        if(index !== $element.data('lastIndex')) {//Has latest movement align the element with the next grid cell?
            functionList[index](index, $element);//Call the selected function.
            $element.data('lastIndex', index);//Remember index so it can be tested mext time.
        }
    });
});
$(function() {
    //(Existing) function that moves the element must trigger the custom 'hasMoved' event after the postition has been changed.
    function moveElement() {
        ...
        ...
        ...
        myElement.trigger('hasMoved');//loosely coupled 'hasMoved' functionality.
    }
    var movementInterval = setInterval(moveElement, 100);
});

正如您所看到的,松耦合的一个优点是,函数和调用它的代码可以在不同的作用域中——.on('hasMoved', function() {...}myElement.trigger('hasMoved')在不同的$(function(){...})结构中。

如果您想添加其他函数来更改myElement的位置(例如,第一个、上一个、下一个、最后一个函数),那么在移动元素后,它们只需触发"hasMoved"即可确保调用二十多个函数中的适当一个,而无需担心作用域。

您唯一需要确保的是,您的二十多个函数的作用域是这样的,即它们可以由自定义事件处理程序调用(即,它们在同一作用域或外部作用域中,直到并包括全局作用域)。

我不得不做出许多假设,所以上面的代码不会100%正确,但希望它能为您提供一条前进的道路。