是否可以测试scrollIntoView浏览器兼容性?

Sab*_*ste 4 javascript jquery js-scrollintoview

我正在寻找一种方法来scrollIntoView对用户浏览器的功能进行实时测试.这不是一个" caniuse "检查; 相反,我希望有优雅的退化.我正在使用jQuery,并希望使用preventDefault()if scrollIntoView功能.

我开始时:

        if (window.scrollIntoView) {
            e.preventDefault();
            $('p#result').text('scrollIntoView is available');
        } else {
            $('#result').text('scrollIntoView is not available');
        }
Run Code Online (Sandbox Code Playgroud)

但我看到那window.scrollIntoViewundefined检查员.但是,因为scrollIntoView有效(在我的Chrome和FireFox版本中),它不应该是未定义的.我还有什么其他选择可以看看用户的浏览器是否支持该功能?

Ste*_*ren 17

检查scrollIntoView是否仅支持布尔值true/false还是支持平滑滚动的行为也很方便.

var isSmoothScrollSupported = 'scrollBehavior' in document.documentElement.style;
if(isSmoothScrollSupported) {
    element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});    
} else {
    element.scrollIntoView(false);
}
Run Code Online (Sandbox Code Playgroud)

  • 不是相反吗?即只有当'isSmoothScrollSupported`为'true`时才将对象传递给`scrollIntoView()`? (4认同)
  • @Benjamin更新我的答案。谢谢你的评论 (2认同)

Dre*_*Jex 8

我发现至少对于 WaterFox 浏览器(可能还有更多),正如Stefan van de Vooren建议的那样,scrollBehavior 确实存在于 document.documentElement.style 中,但浏览器会抛出以下错误:

TypeError: 'block' member of ScrollIntoViewOptions 'center' is not a valid 
value for enumeration ScrollLogicalPosition.
Run Code Online (Sandbox Code Playgroud)

一个简单的 try-catch 语句为我们解决了这个问题:

try {
   element.scrollIntoView({
     behavior: "smooth",
     block: "center"
   });
} catch (error) {
   //fallback to prevent browser crashing
   element.scrollIntoView(false);
}
Run Code Online (Sandbox Code Playgroud)


lla*_*ama 7

方法用于元素,因此您可以检查document.documentElement.scrollIntoView.