From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../api/globaleventhandlers/onscroll/index.html | 126 +++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 files/zh-cn/web/api/globaleventhandlers/onscroll/index.html (limited to 'files/zh-cn/web/api/globaleventhandlers/onscroll') diff --git a/files/zh-cn/web/api/globaleventhandlers/onscroll/index.html b/files/zh-cn/web/api/globaleventhandlers/onscroll/index.html new file mode 100644 index 0000000000..83038201e3 --- /dev/null +++ b/files/zh-cn/web/api/globaleventhandlers/onscroll/index.html @@ -0,0 +1,126 @@ +--- +title: GlobalEventHandlers.onscroll +slug: Web/API/GlobalEventHandlers/onscroll +tags: + - API + - HTML DOM + - 属性 +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +
{{ ApiRef("HTML DOM") }}
+ +

元素的 scroll 事件处理函数。

+ +

语法

+ +
element.onscroll = functionReference
+ +

参数

+ +

functionReference 是一个函数的引用。当该元素滚动时,会执行该函数。

+ +
+

注意:不要将onscroll 与 {{domxref("GlobalEventHandlers.onwheel", "onwheel")}}混淆。onwheel鼠标滚轮旋转, 而onscroll 处理的是对象内部内容区的滚动事件。

+
+ +

 

+ +

示例

+ +
<!DOCTYPE html>
+<html lang="en">
+  <head>
+  <meta charset="UTF-8" />
+  <style>
+  #container {
+    position: absolute;
+    height: auto;
+    top: 0;
+    bottom: 0;
+    width: auto;
+    left: 0;
+    right: 0;
+    overflow: auto;
+  }
+
+  #foo {
+    height:1000px;
+    width:1000px;
+    background-color: #777;
+    display: block;
+  }
+
+  </style>
+  </head>
+  <body>
+    <div id="container">
+      <div id="foo"></div>
+    </div>
+
+    <script type="text/javascript">
+      document.getElementById('container').onscroll = function() {
+        console.log("scrolling");
+      };
+    </script>
+  </body>
+</html>
+
+ +

{{ EmbedLiveSample('示例') }}

+ +

Example

+ +

这个示例能说明更多问题

+ +

This example monitors scrolling on a {{HtmlElement("textarea")}}, and logs the element's vertical scroll position accordingly.

+ +

HTML

+ +
<textarea>1 2 3 4 5 6 7 8 9</textarea>
+<p id="log"></p>
+ +

CSS

+ +
textarea {
+  width: 4rem;
+  height: 8rem;
+  font-size: 3rem;
+}
+ +

JavaScript

+ +
const textarea = document.querySelector('textarea');
+const log = document.getElementById('log');
+
+textarea.onscroll = logScroll;
+
+function logScroll(e) {
+  log.textContent = `Scroll position: ${e.target.scrollTop}`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example", 700, 200)}}

+

注意

+ +

当用户滚动某个元素的内容时 scroll 事件将会被触发。Element.onscroll 同等于 element.addEventListener("scroll" ... )。

+

规范

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Events", "#event-type-scroll", "onscroll")}}{{Spec2("DOM3 Events")}}Initial definition
-- cgit v1.2.3-54-g00ecf