确定元素是在页面折叠上方还是下方 [英] Determine if element is either above or below fold of page

查看:23
本文介绍了确定元素是在页面折叠上方还是下方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些页面有多个输入框,用户可以在其中输入文本.其中一些需要在单击下一步"按钮之前填写.我有验证错误弹出供用户查看但是如果问题是否离开页面我希望页面滚动到它而不是他们必须搜索丢失/错误的字段.

I have some pages that have multiple input boxes that users can enter text into. Some of these are required to fill in before they click the 'next' button. I have validation errors popping up for the user to see however if the question if off the page I would like the page to scroll to it instead of them having to search for the missing/wrong field.

我有一个滚动到位,但我无法确定要滚动到哪个元素的哪个元素.例如,如果输入位于页面折叠上方,我想滚动到标签,以便他们可以看到错误和输入.但如果它低于折叠,我想选择输入,以便显示在折叠上方.有意义吗?

I have a scroll to in place, but I am having trouble ascertaining what element what element to scroll to. For example if the input in above the fold of the page I would like to scroll to the label so they can see the error and the input. But if it is below the fold I would then like to select the input so that will show above the fold. Does that make any sense?

我想我真正想问的是,有没有办法确定元素在页面上的位置.如果它在折叠上方滚动到标签,但如果它在折叠下方则滚动到输入?

I guess what I'm really asking is, is there a way to determine where the element is on the page. And if it is above the fold scroll to the label, but if it is below the fold then scroll to the input?

现在我只是滚动到错误的输入字段.

Right now I am just scrolling to error's input field.

$(".container-content").mCustomScrollbar("scrollTo",$('.container-content').find('input.error:first')); //Yes I am using a plugin for the scroll

如果我只是滚动到标签,那么它看起来像这样.

if I just scroll to the label then it looks like this.

推荐答案

你可以使用这个功能:Jsfiddle

You can use this function: Jsfiddle

function isElementInViewport (el) {
    var rect = el[0].getBoundingClientRect();
    return (rect.top>-1 && rect.bottom <= $(window).height());
}

最初发布 这里

新的 api 只需 11 个额外步骤即可使用,哈哈https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Browser_compatibility

New api which you can use in just 11 extra steps lol https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Browser_compatibility

这篇关于确定元素是在页面折叠上方还是下方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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