我正在使用Twitter Bootstrap的表单,该表单使用固定在顶部的导航菜单(滚动页面,但保持固定在它的顶部)和http://reactiveraven.github.com/jqBootstrapValidation/用于简单的表单验证样式。
然而,我遇到的问题是,当弹出一个验证气球说“请填写此字段”时,浏览器会向上滚动到输入框位于页面顶部的位置。在正常情况下,这很好,但由于我的菜单设置,它是隐藏的。有什么方法可以接管这个滚动并为它添加一个偏移量来防止这种情况发生吗?
答案 0 :(得分:7)
我正在使用完全相同的设置,我发现使用form
元素没有简单的方法。我的黑客是要注意一个无效的input
/ select
/ textarea
,然后从中获取一些火。这不是最好的解决方案,特别是对于大量无效输入,但它帮助我完成了我需要的东西。希望其他人会来,并能够清理一下。
function scrollToInvalid() {
// Height of your nav bar plus a bottom margin
var navHeight = 60;
// Offset of the first input element minus your nav height
var invalid_el = $('input:invalid').first().offset().top - navHeight;
// If the invalid element is already within the window view, return true. If you return false, the validation will stop.
if ( invalid_el > (window.pageYOffset - navHeight) && invalid_el < (window.pageYOffset + window.innerHeight - navHeight) ) {
return true;
} else {
// If the first invalid input is not within the current view, scroll to it.
$('html, body').scrollTop(invalid_el);
}
}
$('input').on('invalid', scrollToInvalid);
答案 1 :(得分:0)
这可以通过 html 元素上的简单 css 来完成
html {
scroll-padding-top: 100px;
}
如果您有粘性页脚,请类似地使用 scroll-padding-bottom: 100px;
适用于所有现代浏览器,当然 IE 除外 在这里查看更多信息 https://css-tricks.com/almanac/properties/s/scroll-padding/