JavaScript Jquery 事件触发的函数一次执行,而不是在正确的时间执行

JavaScript Jquery function that is triggered on event executes all at once instead of right time

我制作了一个函数,当用户在页面上的某个元素上滚动时会触发该函数。在这种情况下,当用户滚动到一个 id 然后它淡入。问题是它们在第一次滚动时同时淡入,而不是当他们到达应该允许它淡入的元素时!请帮我实现我的功能。

非常感谢

var selected={
   //// Storing selectors
   items:[],
   /// Function that stores items and hides them from the page
   selectFunc: function(select) {
   //// Store selected element    
   selected.items.push(select);
   /// hide selector from the page    
    $(select).hide();    
   }
};
//// Function triggeres on scroll    
$(window).scroll(function() {


   /// loops trough the selected elements
   for(i=0; i<selected.items.length; i++){    
   var currentItem = selected.items[i];

       ///// calculates your position and item position
       var hT = $(currentItem).offset().top,
          hH = $(currentItem).outerHeight(),
          wH = $(window).height(),
          wS = $(this).scrollTop();
                 ////// check if you are in the position
                   if (wS > (hT+hH-wH)){
                   $( currentItem ).fadeIn( 2500 );
                 }
           }
   });    

   //// Using my function to select id about and p element in it.  
selected.selectFunc("#about p");
selected.selectFunc("#about input");

在您的 for 循环中,您正在对 selected.items 中的每个元素进行迭代。里面有什么?两个字符串:“#about p”和“#about input”。 因此,对于这些选择器中的每一个,您都显示它们。您需要分别获取每个元素。

另一个问题是,隐藏这些元素意味着它们没有占用页面上应有的 space,因此您可能无法向下滚动。您可以通过更改它们的不透明度而不是使它们 display:none.hide() 在做什么)来解决这个问题。

这是您的代码,经过一些修改:

var selected = {
    //// Storing selectors
    items: [],
    /// Function that stores items and hides them from the page
    selectFunc: function(select) {
        //// Store selected element
        var items = $(select);
        for (var i = 0, l = items.length; i < l; i++) selected.items.push(items[i]);
        /// hide selector from the page    
        items.css('opacity', 0);
    }
};
//// Function triggeres on scroll    
$(window).scroll(function() {
    /// loops trough the selected elements
    for (i = 0; i < selected.items.length; i++) {
        var currentItem = selected.items[i];
        ///// calculates your position and item position
        var hT = $(currentItem).offset().top,
            hH = $(currentItem).outerHeight(),
            wH = $(window).height(),
            wS = $(this).scrollTop();
        ////// check if you are in the position
        if (wS > (hT + hH - wH)) {
            $(currentItem).animate({
                'opacity': 1
            }, 2500);
        }
    }
});

//// Using my function to select id about and p element in it.  
selected.selectFunc("#about p");
selected.selectFunc("#about input");

// Simulating a scroll to show the first elements
$(window).scroll();

JS Fiddle Demo