ヤッハロー、Kaiqisanすうう、一つふつうの学生プログラマである. When the page is too long, the scroll wheel will be generated. This chapter will talk about the scroll wheel event.
Sometimes, when we write some events, we need to determine the block boundary (using offsetTop, offsetLeft) to achieve certain effects (drag and move, etc.), but if there is a scroll wheel in the web page, then when the scroll wheel scrolls, the boundary The judgment will produce errors, and the user experience will plummet. So this scroll wheel event can perfectly solve this problem.
Obtaining a wheel event is very simple.
window.onscroll = () => {
let a = document.documentElement.scrollTop || document.body.scrollTop; // 兼容
console.log(a)
}
Every time the wheel rolls, its distance from the top will be monitored.
scrollTop
This attribute is the key here . Keep in mind that it corresponds to the scroll wheel that slides up and down. scrollLeft
This property can be used if the scroll wheel that slides left and right is produced .
but
The above method can only monitor the scroll wheel generated by the body tag. If a tag element in the body generates a scroll wheel, the above window.onscroll
cannot be detected.
<div class="demo">
<div class="inner-demo">ddd</div>
</div>
.demo {
width: 500px;
height: 400px;
border: 1px solid #000000;
overflow: auto;
}
.inner-demo {
width: 300px;
height: 900px; /* 内部元素高度更高,使demo元素产生上下滑动的滚轮 */
}
window.onscroll = () => {
console.log('ok');
}
Then, we will find that this method cannot be triggered at all .
This is the problem of the basic principles of DOM. It needs to be solved in this way. It is necessary to assign monitors to the elements that produce the scroll wheel .
let objDemo = document.getElementsByClassName('demo')
objDemo[0].onscroll = (e) => {
console.log(objDemo.scrollTop);
}
Besides
In the event the wheel, there are two available attributes scrollHeight
scrollWidth
which represent the actual content of the width, height, width of the line does not include, the contents of the object will vary over the visible region becomes large
to sum up
No summary