繁体   English   中英

在 scrollTo 上禁用 css 滚动平滑

[英]disable css scroll smooth on scrollTo

我的元素有 css scroll-behavior:smooth ,我使用它来平滑 hash “a href”链接。

我希望页面首先加载到页面上的固定 position 上,这意味着它不会在第一次加载到 position 时“平滑”滚动,并且只能在之后使用它。

我不想使用任何 setTimeOut hack,我知道 scrollTo 具有广泛支持的“选项”,但我找不到任何类型的“行为”会覆盖 css 平滑度。

如果我的问题正确 - 没有任何 setTimeout - 我首先想到的是使用 JS 简单地将 class (例如: smoothScroll-init )添加到所有class="smoothScroll"元素:

HTML:

<div class="smoothScroll">Still not smooth...</div>

CSS:

/* Will be added by JS on DOM ready */
.smoothScroll-init {           
  scroll-behavior: smooth;
}

JS:

// DOM is ready
// Add class "smoothScroll-init" to all class "smoothScroll" elements:
document.querySelectorAll(".smoothScroll").forEach(EL => EL.classList.add("smoothScroll-init"));

如果您要定位特定元素并快速滚动到视图中,请使用: Element/scrollIntoView使用{behavior: "auto"}选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM