jQuery window scroll event does not fire up

2019-01-17 19:12发布

I'm trying to implement a simple "stay inside the viewport" behaviour to a div via jquery. For that i need to bind a function to the scroll event of the window, but i can't seem to get it to fire up: nothing happens. I've tried a simple alert(), console.log() no dice. An idea what i'm doing wrong?

This code :

$(window).scroll(function () {  
            console.log("scrolling");           
});

sits in script.js, located at the very bottom of my html file

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

UPDATE Test URL: http://pixeline.eu/test/menu.php

7条回答
Root(大扎)
2楼-- · 2019-01-17 19:45

OK, worked it out.

Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. the easiest fix for this is bind the event to the thing that is scrolling which in your case is div#page.

So its easy as changing:

$(document).scroll(function() {  // OR  $(window).scroll(function() {
    didScroll = true;
});

to

$('div#page').scroll(function() {
    didScroll = true;
});

Cheers
Charlie

查看更多
不美不萌又怎样
3楼-- · 2019-01-17 19:46

Thr solution is:

 $('body').scroll(function(e){
    console.log(e);
});
查看更多
唯我独甜
4楼-- · 2019-01-17 19:50

My issue was I had this code in my css

html,
body {
    height: 100%;
    width: 100%;
    overflow: auto;
}

Once I removed it, the scroll event on window fired again

查看更多
仙女界的扛把子
5楼-- · 2019-01-17 19:55

Nothing seemd to work for me, but this did the trick

$(parent.window.document).scroll(function() {
    alert("bottom!");
});
查看更多
该账号已被封号
6楼-- · 2019-01-17 20:01

To whom its just not working to (like me) no matter what you tried: <element onscroll="myFunction()"></element> works like a charm

exactly as they explain in W3 schools https://www.w3schools.com/tags/ev_onscroll.asp

查看更多
看我几分像从前
7楼-- · 2019-01-17 20:01

Try 1) declaring your jQuery <script> in the <head> or 2) wrap your .scroll() event with $(document).ready() or 3) both

查看更多
登录 后发表回答