csdn 里的一篇文章,挺短的。
JS 获取滚动条位置
本文的结果能分别在最新版的chrome 和Fire Fox 中运行。
MDN里有关于Element.ScrollTop属性的资料:
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollTop
运用另一种方法绑定事件
document.addEventListener('scroll', function(e){
console.log(document.documentElement.scrollTop);
});
如果要绑定整个页面的滚动,需要联系html元素
这个很奇怪,事件必须绑定在document上,但是scrolltop的值在html元素上取得。
但是对于其他的元素,事件绑定在该元素上,并且scrollTop的值也是在他上面取得。
例如取得一个id为 ts 的scrollTop值。
<div id='ts' style="position: relative; top: 300px; 300px; height: 300px; background-color:black; overflow:scroll;"> <div style=" 200px; height: 500px; background-color:rgb(160, 159, 159);"></div> </div>
需要:
document.querySelector("#ts").addEventListener('scroll', function(e){ console.log(e.target.scrollTop); })
这里运用了event元素的target属性,该属性表示事件绑定的元素。
在最后我写了一个小小的效果(确实没灵感了)
根据scrollbar的位置改变文字的透明度。
代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> html, body{ height: 200%; background-color: rgb(243, 243, 243); } </style> </head> <body> <div id="ap" style="text-align: center; font-size: 24px; font-family: consolas; margin-top: 600px;"> APPEAR AND DISAPPEAR </div> <script> var ap = document.querySelector('#ap'); document.addEventListener('scroll', function(e){ var level =1- document.documentElement.scrollTop/600; ap.style.opacity = level; }); </script> </body> </html>
肯定能用这个写出更加炫酷的动画效果的,大家不要像我一样寒酸。。。
2017/6/26
当元素使用了overflow:hidden的时候,scroll事件不再触发