ScrollToOptions

CSSOM View 规范的 ScrollToOptions 字典(dictionary)当中的属性用于指定一个元素应该滚动到哪里,以及滚动是否应该平滑。

一个 ScrollToOptions 字典可以作为参数提供给下面的方法:

属性

ScrollToOptions.top
指定 window 或元素 Y 轴方向滚动的像素数。
ScrollToOptions.left
指定 window 或元素 X 轴方向滚动的像素数。
ScrollToOptions.behavior
指定滚动是否应该平滑进行,还是立即跳到指定位置。该属性实际上定义在 ScrollOptions 字典上,它通过 ScrollToOptions 实现。

示例

在我们的 scrolltooptions 示例中(在线查看 ),包含一个表单,允许用户输入三个值——两个数值表示 left 和 top 属性(即沿 X 和 Y 轴方向滚动后的位置),以及一个表示是否开启平滑滚动的复选框。

当提交表单时,会运行事件监听器,该事件监听器会把输入的值写入 ScrollToOptions 字典,然后传入 Window.ScrollTo() 方法,并调用:

form.addEventListener('submit', (e) => {
  e.preventDefault();
  scrollOptions = {
    left: leftInput.value,
    top: topInput.value,
    behavior: scrollInput.checked ? 'smooth' : 'auto'
  }

  window.scrollTo(scrollOptions);
});

规范

Specification Status Comment
CSS Object Model (CSSOM) View Module
ScrollToOptions
Working Draft

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
ScrollToOptionsChrome Full support 45Edge No support NoFirefox Full support YesIE No support NoOpera Full support 32Safari No support NoWebView Android Full support 45Chrome Android Full support 45Firefox Android Full support YesOpera Android Full support 32Safari iOS No support NoSamsung Internet Android Full support Yes
behaviorChrome Full support 45Edge No support NoFirefox Full support YesIE No support NoOpera Full support 32Safari No support NoWebView Android Full support 45Chrome Android Full support 45Firefox Android Full support YesOpera Android Full support 32Safari iOS No support NoSamsung Internet Android Full support Yes
leftChrome Full support 45Edge No support NoFirefox Full support YesIE No support NoOpera Full support 32Safari No support NoWebView Android Full support 45Chrome Android Full support 45Firefox Android Full support YesOpera Android Full support 32Safari iOS No support NoSamsung Internet Android Full support Yes
topChrome Full support 45Edge No support NoFirefox Full support YesIE No support NoOpera Full support 32Safari No support NoWebView Android Full support 45Chrome Android Full support 45Firefox Android Full support YesOpera Android Full support 32Safari iOS No support NoSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support