$(window).resize()在移动设备上滚动时执行 [英] $(window).resize() executes when scrolling on mobile devices

查看:127
本文介绍了$(window).resize()在移动设备上滚动时执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

HTML

<div><p>A lot of text that goes off the page so you have to scroll down.........</p></div>

JavaScript

JavaScript

$(window).resize(function(){
    $("div").append("<p>appended</p>");
});

这可以正常工作,并按预期将其添加到调整大小的段落中,但是当我向下滚动时,它也会被追加.这意味着当我到达原始文本的末尾时,会有大约20个附加段落.

This works and appends the paragraph as expected on resize, but it is also appended when I scroll down. This means when I get to the end of the original text there is about 20 appended paragraphs.

这仅在移动设备上发生(到目前为止,我已经检查了Chrome,Safari和Firefox),而不是在台式机浏览器上发生.

This is only happening on mobile devices (so far I've checked Chrome, Safari and Firefox), not on desktop browsers.

有没有一种方法可以阻止这种情况的发生,并且仅在调整窗口(您看到的)大小时才添加段落? 还是只是调整大小中的代码如此频繁地执行?

Is there a way to stop this happening and have the paragraph appended only when the window (that you see) is resized? Or maybe only have the code within the resize execute every so often?

谢谢.

推荐答案

移动设备的问题在于,它们具有滚动浏览器时隐藏的浏览器工具栏,这会导致屏幕切换(激活调整大小事件),这意味着您必须对代码进行一些验证,并检测为什么触发了resize事件.

The problem with mobile devices is that they have the browser toolbars that are hidden when you scroll and this leads to screen change (activates the resize event) and this means that you have to make some validations to your code and detect why was the resize event fired.

我使用的一种方法是保存窗口宽度并检查正确的窗口宽度是否相同或已更改.如果更改,则意味着应该进行附加操作(在您的情况下).

One way I have used is by saving the window width and checking if the correct window width is the same or changed. If it changes then it means that the append should happen (in your case).

var dwidth = $(window).width();

$(window).resize(function(){
    var wwidth = $(window).width();
    if(dwidth!==wwidth){
         dwidth = $(window).width();
         console.log('Width changed');
    }
});

这篇关于$(window).resize()在移动设备上滚动时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆