Javascript 是否可以测试scrollIntoView浏览器兼容性?
我正在寻找一种方法来对我的用户浏览器的Javascript 是否可以测试scrollIntoView浏览器兼容性?,javascript,jquery,js-scrollintoview,Javascript,Jquery,Js Scrollintoview,我正在寻找一种方法来对我的用户浏览器的scrollIntoView功能进行实时测试。这不是一张“支票”;相反,我想要优雅的堕落。我使用的是jQuery,如果scrollIntoView功能正常,我想使用preventDefault() 我从以下几点开始: if (window.scrollIntoView) { e.preventDefault(); $('p#result').text('scrollIntoView is ava
scrollIntoView
功能进行实时测试。这不是一张“支票”;相反,我想要优雅的堕落。我使用的是jQuery,如果scrollIntoView功能正常,我想使用preventDefault()
我从以下几点开始:
if (window.scrollIntoView) {
e.preventDefault();
$('p#result').text('scrollIntoView is available');
} else {
$('#result').text('scrollIntoView is not available');
}
但是我看到窗口。scrollIntoView
在inspector中是未定义的。但是,因为scrollIntoView
可以工作(在我的Chrome和FireFox版本中),所以它不应该是未定义的。如果用户的浏览器支持该功能,我还可以查看哪些其他选项?这是关于元素的,因此您可以检查document.documentElement.scrollIntoView
也可以方便地检查scrollIntoView是否仅支持布尔真/假或还支持平滑滚动的行为
var isSmoothScrollSupported = 'scrollBehavior' in document.documentElement.style;
if(isSmoothScrollSupported) {
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
} else {
element.scrollIntoView(false);
}
我发现,至少对于Waterbox浏览器(可能还有更多),正如建议的那样,document.documentElement.style中确实存在scrollBehavior,但浏览器会抛出以下错误:
TypeError: 'block' member of ScrollIntoViewOptions 'center' is not a valid
value for enumeration ScrollLogicalPosition.
一个简单的try-catch语句为我们解决了这个问题:
try {
element.scrollIntoView({
behavior: "smooth",
block: "center"
});
} catch (error) {
//fallback to prevent browser crashing
element.scrollIntoView(false);
}
您可以这样检查:
if (typeof document.body.scrollIntoView === 'function') {
// Do smth.
yourNode.scrollIntoView();
}
窗口
没有此方法的魅力。我使用了document.body.scrollIntoView
,代码执行正确。非常感谢。不是正好相反吗?i、 e.仅当支持平滑滚动时,才将对象传递给滚动视图()
,为true
?@Benjamin更新我的答案。谢谢你的评论,好支票。在Safari中,允许使用选项
,但它不支持滚动行为
,因此上述检查将失败,并将退回到对用户更糟糕的替代行为。这就是为什么我们更喜欢使用try/catch now的其他解决方案: