我正在寻找一种方法来对用户浏览器的Validator<ParentThing>
功能进行实时测试。这不是“caniuse”检查;相反,我希望有优雅的退化。我正在使用jQuery,如果scrollIntoView正常运行,我想使用scrollIntoView
。
我开始时:
preventDefault()
但我在检查器中看到 if (window.scrollIntoView) {
e.preventDefault();
$('p#result').text('scrollIntoView is available');
} else {
$('#result').text('scrollIntoView is not available');
}
为window.scrollIntoView
。但是,因为undefined
有效(在我的Chrome和FireFox版本中),所以不应该定义它。如果用户的浏览器支持该功能,我还有什么其他选择吗?
答案 0 :(得分:11)
检查scrollIntoView是否仅支持布尔值true / false或是否支持平滑滚动行为也很方便。
var isSmoothScrollSupported = 'scrollBehavior' in document.documentElement.style;
if(isSmoothScrollSupported) {
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
} else {
element.scrollIntoView(false);
}
答案 1 :(得分:2)
method是元素,因此您可以查看document.documentElement.scrollIntoView
。
答案 2 :(得分:2)
I found that at least for the WaterFox browser (and likely a few more), scrollBehavior did exist in document.documentElement.style as Stefan van de Vooren suggests, yet the browser would throw the following error:
TypeError: 'block' member of ScrollIntoViewOptions 'center' is not a valid
value for enumeration ScrollLogicalPosition.
A simple try-catch statement solved the issue for us:
try {
element.scrollIntoView({
behavior: "smooth",
block: "center"
});
} catch (error) {
//fallback to prevent browser crashing
element.scrollIntoView(false);
}
答案 3 :(得分:1)
您可以这样检查它:
if (typeof document.body.scrollIntoView === 'function') {
// Do smth.
yourNode.scrollIntoView();
}