首页 新闻 会员 周边

jQuery/JS 的 window.scroll 在 FireFox 不正常

0
悬赏园豆:100 [已解决问题] 解决于 2015-03-27 18:52

请问以下这段 jQuery 的 window onscroll 代码,
在 IE、Chrome 正常,鼠标卷一次,才会 alert 一次。
但在 FireFox 疯狂,鼠标卷一次,就会 alert 非常多次。

请问此 window onscroll 和 FireFox 不和的问题,要怎么解决?


我是希望 FireFox 能和 IE、Chrome 一样,能够鼠标卷一次,只要 alert 一次就好。

(若网友愿给有用的提示,我亦会给您点数)

感谢各位。

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   
    <script type="text/javascript">
        $(window).scroll(function () {
            alert('hi, ' + $(window).scrollTop());
        });
    </script>
</head>
<body>
 这里的内容很长(亦可用 C# 去 Response.Write 很长的内容)
</body>
</html>
WizardWu的主页 WizardWu | 小虾三级 | 园豆:1402
提问于:2015-03-25 18:28
< >
分享
最佳答案
1

不同浏览器的行为会导致这个问题,而且在Scroll里面添加事件是非常不推荐的,如果需要用的话,请参考以下文章:

 

It's a very, very, bad idea to attach handlers to the window scroll event. Depending upon the browser the scroll event can fire a lot and putting code in the scroll callback will slow down any attempts to scroll the page (not a good idea). Any performance degradation in the scroll handler(s) as a result will only compound the performance of scrolling overall. Instead it's much better to use some form of a timer to check every X milliseconds OR to attach a scroll event and only run your code after a delay (or even after a given number of executions - and then a delay).

 

http://ejohn.org/blog/learning-from-twitter/

收获园豆:100
XiaoFaye | 老鸟四级 |园豆:3087 | 2015-03-26 07:51

采用了類似的解決方式:

var tur = true;

function haha(){
    alert("haha"); 
    tur = true;
}

window.onscroll = function(){
    //鼠标滚动一次,这里会被不正常地重复执行,尤其 Firefox 非常严重

    if (tur == true) { 
        // 0.5 秒后,自动设为 true,避免重复执行、重复访问数据库
        setTimeout(haha, 500); 

        //在这里访问数据库

        tur = false;
    }
} 

 

WizardWu | 园豆:1402 (小虾三级) | 2015-03-27 18:58
其他回答(1)
1

发现没有,IE和Chrome在鼠标滚动的时候,scroll是“一节一节”的滚动,而ff是很平滑的滚动,所以不断触发。

跟浏览器设置有关。

上位者的怜悯 | 园豆:172 (初学一级) | 2015-03-31 16:58

谢谢您告知

支持(0) 反对(0) WizardWu | 园豆:1402 (小虾三级) | 2015-04-03 19:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册