在 JavaScript 中禁用滚动
在今天的文章中,我们将了解如何使用纯 JavaScript 禁用滚动事件。
在 JavaScript 中的滚动
滚动是在屏幕上从右到左或上下移动文本以显示不能包含在单个显示图像中的文本的行为。滚动是图像、视频或文本在屏幕上的垂直或水平滑动运动。
滚动可以双向进行,有或没有用户干预。大多数应用程序和智能设备都提供此功能,允许你显示太大的内容而无法完全适应屏幕。
它被认为是导航的基本方法之一。
滚动通常使用鼠标(通常带有内置滚轮)或台式机和笔记本电脑上的触控板完成。在移动设备上,你通常使用手指或触控笔进行滚动。
在 JavaScript 中使用 scrollTo()
禁用滚动
Window.scrollTo()
是 JavaScript 提供的一种内置方法,可以滚动到文档中的一组特定坐标。
语法:
window.scrollTo(x - cord, y - cord)
window.scrollTo(options)
你希望显示在左上角的文档的水平
轴上的 x-cord
坐标。沿着要在左上角显示的文档的垂直
轴的 y-cord
坐标。
作为一个选项,scrollTo
函数采用以下参数。
top
属性指定沿 Y 轴滚动窗口或元素的像素数。left
属性指定沿 X 轴滚动窗口或元素的像素数。behavior
属性指定滚动是否应该平滑(柔和)或是否应该在单次跳转中立即发生(自动是默认值)。
在 window.scrollTo() 的文档中查找更多信息。
让我们举一个带有 2 个按钮的示例,一个将启用滚动,另一个将禁用滚动。内容渲染完成后,你可以根据需要调用此功能。
例子:
<button type="button" id="disabled">Disable scrolling</button>
<button type="button" id="enabled">Enable scrolling</button>
<div>scroll The page</div>
div {
background-color: #f0f0f0;
height: 150vh;
line-height: 150vh;
text-align: center;
}
function scrollEvent() {
window.scrollTo(0, 0)
}
disabled.addEventListener(
'click', () => {window.addEventListener('scroll', scrollEvent)})
enabled.addEventListener(
'click', () => {window.removeEventListener('scroll', scrollEvent)})
addEventListener()
是 JavaScript 提供的集成方法。此方法注册一个事件侦听器。它是 EventTarget
接口的一个方法。
每当在目标上检测到指定的事件时,就会调用我们配置的函数。
我们附加了 2 个事件侦听器来侦听按钮的单击事件。一旦用户点击 disable
按钮,我们将滚动到左上角位置,并且总是如此。
一旦用户点击 enabled
按钮,我们移除事件监听器,它监听滚动事件,并且坐标可以自由移动。
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。