2017-02-11 13 views
1

の複数のインスタンスに適用され、私は要素がビューポートであるかどうかを検出する機能を使用しようとしてきた:JavascriptをgetBoundingClientRect() - クラス

function isElementInViewport (el) { 
    var rect = el[0].getBoundingClientRect(); 
    return (rect.top>-1 && rect.bottom <= $(window).height()); 
} 
var s= $('.special'), 
    y = $('.status'); 

$(window).on('scroll resize', function(){ 
    if(isElementInViewport(s)) 
    { 
     setTimeout(function(){ 
      if(isElementInViewport(s)) 
      { 
      var offer_id = s.data("offer-id"); 
      alert(offer_id); 
      y.text('Yes'); 
     } 
     }, 3000); 
    } 
    else 
    { 
     y.text('No'); 
    } 
}); 

は、残念ながら、これは最初のインスタンスのみのために働くようですクラス「特別」のどのようにしてそのクラスのすべてのインスタンスに適用するのですか?

速いスクロールでトリガーするのを防ぐため、3秒の遅延を追加しました。ここで

は、私の進捗状況のjsfiddleです:jqueryのeachを使用してhttp://jsfiddle.net/azjbrork/6/

+2

コレクションのすべての要素をループしたい場合にのみ、なぜ 'el [0]'で呼び出すのですか? – Bergi

+0

@Bergi機能は私のものではありません。私はjavascriptの練習で学ぶことを試みている相対初心者です... –

+1

'el'はjqueryオブジェクトです - この場合' $( '。special') 'と' getBoundingClientRect( ' ); 'は、jQueryオブジェクトの最初のコンポーネントでのみ呼び出すことができる純粋なjs関数です。したがって '$( '。special')'は '$( '。special')[0] .....'になります。この場合は 'el [0]'です。 – Sam0

答えて

2

我々は.specialクラスの各インスタンスに関数を実行し、それに応じて折り返し報告することができます(以下抜粋):

function isElementInViewport(el) { 
 
    var rect = el[0].getBoundingClientRect(); 
 
    return (rect.top > -1 && rect.bottom <= $(window).height()); 
 
} 
 
var s = $('.special'), 
 
    y = $('.status'); 
 

 
$(window).on('scroll resize', function() { 
 
    s.each(function() { 
 
    var $this = $(this); 
 
    if (isElementInViewport($this)) { 
 
     setTimeout(function() { 
 
     if (isElementInViewport($this)) { 
 
      var offer_id = $this.data("offer_id"); 
 
      // advise using an underscore instead of a hyphen in data attributes 
 
      //  alert(offer_id); // reported in text below 
 
      y.text('Yes : ' + offer_id); 
 
     } 
 
     }, 200); 
 
    } else { 
 
     // y.text('No'); // omit this line otherwise it will always report no (subsequent out of screen divs will overwrite the response) 
 
    } 
 
    }); 
 

 
});
.special { 
 
    width: 80px; 
 
    height: 20px; 
 
    border: 1px solid #f90; 
 
    margin-top: 200px; 
 
} 
 
.status { 
 
    position: fixed; 
 
    right: 2em; 
 
    top: 1em; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div class='special' data-offer_id='a'></div> 
 
<div class='special' data-offer_id='b'></div> 
 
<div class='special' data-offer_id='c'></div> 
 
<div class='special' data-offer_id='d'></div> 
 
<div class='special' data-offer_id='e'></div> 
 
<div class='special' data-offer_id='f'></div> 
 

 

 
<div class='status'></div>

+0

「それぞれ」について教えてくれてありがとう、すごく感謝しました! –

関連する問題