簡體   English   中英

Javascript-三元運算符-比較同一個函數兩次?

[英]Javascript - Ternary Operator - Comparing same function twice?

我有3個變量top, mid, bot分別是div彈出的top, mid, bot ,這取決於div彈出的部分(如果div最高部分,則將記錄top

您需要知道的是,當用戶從頁面頂部向下滾動時,我們要定位某些divs 這三個變量表示每當我們到達div的某個部分時需要記錄的內容。

現在如何重寫console.log三元運算符console.log意義,中間根本沒有運行。

編輯

trgt1 and trgt2是具有類( .column )的2個div。 trgt1是顯示的第一個div,當我們滾動瀏覽div的一半時, trgt2應該彈出。

function onScroll(event){

let top = "Column with id:`id-10` started to become visible on the page."
let mid = "Column with id:`id-50` is now more than 50% visible on the page."
let bot = "Column with id:`id-40` is now fully visible on the page."

targets.forEach(

    function(trgt,index){

          let isVisible = isScrolledIntoView(trgt);

          if (visibleStates[index] != isVisible)

          console.log(`Element index ${index} is now ${isVisible === trgt1 ? top : (isVisible === trgt2 ? mid : bot)}`);

          visibleStates[index] = isVisible;
        }
    );
}

您可以使用在滾動頁面時運行的腳本。 因此,在頁面上添加一個事件偵聽器。然后,您可以消除滾動的抖動,從而控制窗口上允許的噪聲量。我包含的功能是一個有效的消除抖動功能,只需等待幾毫秒即可播放。 然后在將運行代碼放入其中的checkSlide()函數上使用反跳函數。

我知道這不是直接的答案,而是解決問題的另一種方式。 這可能有效。 如果您想按照自己的方式做,那就去吧。

祝好運!

window.addEventListener('scroll', debounce(checkSlide));

function checkSlide(){}

function debounce(func, wait=20, immediate = true){

var timeout; 

//debounce is a higher order function and will return another function 
return function run_code() {
    var context = this;

    //arguments is local variable of a function, refers to all arguments 
    var args = arguments; 

    //variable later is a function
    var later = function(){
        timeout = null;

        //if it is not time zero, apply checkSlide function 
        if(!immediate) func.apply(context, args);
    };

    var Callnow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if(Callnow) func.apply(context, args);
}
}

暫無
暫無

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

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