2016-09-15 82 views
0

当我向下滚动时,scroll事件不会触发。不知道我在这里做错了什么。为什么jQuery滚动事件不会触发?

下面是我的代码:

<style> 
    #scroll { 
    max-height: 100px; 
    overflow-y: auto; 
    width: 647px; 
    margin: auto; 
    } 
</style> 
<body> 
    <div id='scroll'> 
    <p>hello world</p> 
    <p>hello world</p> 
    <p>hello world</p> 
    <p>hello world</p> 
    <p>hello world</p> 
    <p>hello world</p> 
    <p>hello world</p> 
    </div> 
    <script> 
    $(document).on("scroll", "#scroll", function() { 
     console.log("hi"); 
    }); 
    </script> 
</body> 
+1

你拥有包括jQuery的?检查它的一个好方法是在浏览器中打开开发人员工具。 – Rohit

+0

是否出现“滚动”?我不认为有这么小的内容,“滚动”将出现... – Rayon

+0

可能重复[为什么不委派工作滚动?](http://stackoverflow.com/questions/9253904/why-doesnt -delegate工作换滚动) –

回答

1

滚动事件元素不冒泡:MDN: Events scroll

泡沫 不上的元素,但在文件发射时泡沫默认视图

因此,你不能使用事件委托。你总是需要直接添加事件监听器显示有关该事件发生的元素:

$('#scroll').on('scroll', function() { 
} 

或者使用香草JavaScript和这里描述捕捉捕获阶段事件:[...]But, on modern browsers (IE>8), you can capture scroll event to e.g document level or any static container for dynamic element.[...]

0

这是你如何检测scrollingscroll position。希望这会帮助你。请参阅此工作demo.scroll以查看。

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title></title> 
 
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
\t 
 
</head> 
 

 
<style type="text/css"> 
 
body{ 
 
\t height: 1000px; 
 
} 
 

 
div#scroll{ 
 
\t width: 300px; 
 
\t height: 200px; 
 
\t overflow: scroll; 
 
\t background-color: orange; 
 
\t color: white; 
 
\t text-align: center; 
 
\t font-size: 20px; 
 
\t font-family: monospace; 
 
} 
 

 
</style> 
 

 

 
<body> 
 
\t <div id="scroll"> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t <li>one one</li> 
 
\t </div> 
 

 
</body> 
 

 
<script type="text/javascript"> 
 

 
$("div#scroll").scroll(function(){ 
 
\t alert("scrolling"); 
 
\t var scrollPosition = $(this).scrollTop(); 
 
\t alert(scrollPosition); 
 
}); 
 

 

 

 
</script> 
 
</html>

相关问题