2014-12-03 25 views
0

我有一個片段,它在滾動時會檢查元素是否在當前視口中。注意多個元素沒有多個if語句

我現在想要添加多個元素到混合中,但我想避免做多個if語句檢查每個元素,我知道下面的代碼不起作用,但它是我想如何做的一個例子,有沒有辦法這樣做?

var listOfPanels = $('#item2, #item2, #item3, #item4, #item5'); 

$(window).scroll(function(event) { 
    // if the element we're actually looking for exists 
    if (listOfPanels.length){ 

    // check if the element is in the current view using the attached function 
    // and the event hasn't already fired 
    if (isElementInViewport(listOfPanels)) { 

     // do something 
    } 
    } 
}); 
+0

http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433:檢查這個答案是非常有幫助。 – Jai 2014-12-03 10:19:48

+0

@Jai我alreday有viewport snippet,它的多重元素我在 – rogy 2014-12-03 10:23:24

回答

1

試試這個:(從帶來isElementInViewport JS方法:How to tell if a DOM element is visible in the current viewport?

function isElementInViewport(el) { 
    var top = el.offsetTop; 
    var left = el.offsetLeft; 
    var width = el.offsetWidth; 
    var height = el.offsetHeight; 

    while(el.offsetParent) { 
    el = el.offsetParent; 
    top += el.offsetTop; 
    left += el.offsetLeft; 
    } 

    return (
    top < (window.pageYOffset + window.innerHeight) && 
    left < (window.pageXOffset + window.innerWidth) && 
    (top + height) > window.pageYOffset && 
    (left + width) > window.pageXOffset 
); 
} 

var listOfPanels = $('#item2, #item2, #item3, #item4, #item5'); 
$(window).scroll(function(event) { 
    if (listOfPanels.length){ 
    listOfPanels.each(function(){ 
     if (isElementInViewport($(this)[0])) { 
     console.log($(this).attr('id') + ' in viewport'); 
     } 
    }); 
    } 
}); 

希望幫助。

+0

不能做'listOfPanels.each(function(){'那樣的方式,但是它後面的想法是正確的,謝謝! – rogy 2014-12-03 10:36:15

+0

爲什麼可以't'.each()'? – geevee 2014-12-03 10:57:16

+0

因爲它不是一個數組,它是一個列表 – rogy 2014-12-03 16:01:50