2014-02-12 32 views
2

我试图检查从jquery滚动条到达div的时间。 我读了一些类似的问题在stackoverflow,但都只在一个div。 我有4格,高度:100%,我想知道什么时候滚动条通过每隔格。 我试过了,但只适用于第一个div。检查滚动条是否与jquery达到div

HTML:

<body> 
<div id="main"></div> 
<div id="service"></div> 
<div id="clients"></div> 
<div id="about"></div> 
</body> 

CSS:

body, html { 
    height: 100%; 
    padding: 0px; 
    margin: 0px; 
} 
#main { 
    background: red; 
    height: 100%; 
} 
#service { 
    background: green; 
    height: 100%; 
} 
#clients { 
    background: blue; 
    height: 100%; 
} 
#about { 
    background: yellow; 
    height: 100%; 
} 

JS:

$(document).ready(function() { 
    var passed_service = false; 
    var passed_service = false; 
    $('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(event){ 
     if($(window).scrollTop() >= ($("#service").height())){ 
      if(!passed_service){ 
       alert("To #service"); 
       passed_service = true; 
      } 
     } 
     if($(window).scrollTop() >= ($("#service").height() + $("#clients").height())){ 
      if(!passed_clients){ 
       alert("To #clients"); 
       passed_clients = true; 
      } 
     } 
    }); 
}); 

SORRY TO ALL,是我愚蠢的错误,我无法删除的问题:(

回答

4
var passed_service = false; 
var passed_service = false; /* should be 'passed_clients' */ 

^这里是你的问题


此外,而不是相加的div的高度,使用顶部,而不是偏移。

DEMO

$(window).scrollTop() >= $("#service").offset().top 
$(window).scrollTop() >= $("#clients").offset().top 
... 
+0

我上的jsfiddle错,但就是不($(window).scrollTop()> =($(“#service”)。height()+ $(“#clients”)。height()))这个问题在这里: 'code' if { – Riccardo

+0

你是什么意思?有什么问题[这里](http://jsfiddle.net/qXa36/)? – kei

+0

我的错,很抱歉! – Riccardo

0

你永远不声明passed_clients变量。

更改此:

var passed_service = false; 
var passed_service = false; 

这样:

var passed_service = false; 
var passed_clients = false; 

工作小提琴:http://jsfiddle.net/XUEfD/8/

0

工作Demo link

use this: (parseInt($("#service").height()) + parseInt($("#clients").height())) 

$(document).ready(function() { 
var passed_service = false; 
var passed_clients = false; 
$('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(event){ 
    if($(window).scrollTop() >= ($("#service").height())){ 
     if(!passed_service){ 
      alert("To #service"); 
      passed_service = true; 
     } 
    } 

    //console.log($(window).scrollTop()); 
    if($(window).scrollTop() >= (parseInt($("#service").height()) + parseInt($("#clients").height()))){ 
     if(!passed_clients){ 
      alert("To #clients"); 
      passed_clients = true; 
     } 
    } 
}); 
});