簡體   English   中英

當元素到達屏幕上的某個位置時觸發事件

[英]trigger an event when an element reaches a position on the screen

我想根據元素的位置觸發一些功能。 該元素的位置每十分之一秒更改一次。 有兩個功能可以觸發。

我想到了這個偽代碼:

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
     }
}

但是每隔幾秒鍾就會遍歷所有可能的位置,給瀏覽器帶來負擔。 因此,如果有一種方法可以使事件發生。

可能嗎 ?

編輯:在Beetroot-Beetroot評論之后,我必須說,移動的元素僅在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%正確,但是希望它將為您提供前進的道路。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM