滚动时编辑Div(例如在Google文档中) [英] Edit Div when scrolled over (like in google docs)
问题描述
基本上我想编写一些类似google docs主页中的内容
Basically I want to code something as seen in the google docs home
当您打开它时,它具有模板部分,然后是组织部分,然后是您的文档
when you open it up it has the template section then organizing section then your documents
但是当您滚动浏览组织部分时(任何人拥有的日期,日期到a到z),它会手动将其自身添加到导航栏中并添加框阴影
but when you scroll past the organizing section (when, owned by anyone, date, a to z), it manually adds itself to the navbar and adds box shadow
谁能告诉我Google是如何做到的,所以我可以在我的网站上实现它
can anyone tell me how google does it, so i can implement it on my website
滚动太多后(添加到带有框阴影的顶部栏中)之前(与顶部栏分开-没有框阴影)
推荐答案
您只需在用户滚动时添加一个侦听器,然后,如果用户滚动了一定数量的像素,则可以执行某些操作.
You'd simply add a listener for when the user is scrolling, then if the user has scrolled a set amount of pixels do something.
window.addEventListener('scroll', () => {
console.log("scrolled")
}
现在,滚动文本时,"scrolling"文本将记录在控制台中.因此,现在我们需要添加一个if语句,检查您是否已向下滚动到页面的某个位置(以像素为单位进行计算).
Now when scrolling the text "scrolling" will be logged in the console. So now we need to add an if statement, checking if you've scrolled to a certain amount down the page, this is calculated in pixels.
window.addEventListener('scroll', () => {
if (document.body.scrollTop > 50 {
console.log("User Scrolled past 50pixels
}
}
现在,当您向下滚动页面50px时,控制台将对其进行记录.因此,您只需将导航栏的css代码更改为在顶部具有固定位置即可,只要向下滚动到该位置即可,当滚动到50px以上时,请删除该CSS.
Now when you've scrolled 50px down the page the console will log it. So you'd just have to change the css code of the navbar to have a fixed position at the top, as soon as you've scrolled down to it, and when you scroll above 50px remove that CSS.
window.addEventListener('scroll', () => {
if (document.body.scrollTop > 50 {
// Make the div fixed here
} else {
// Remove the css making the div fixed
}
}
当然,可以将50更改为您喜欢的任何数字.例如,在Google文档上,当您向下滚动约205px时,它将使导航固定.
Of course the 50 can be changed to any number you prefer. For example on Google Docs, it makes the nav fixed when you've scrolled about 205px down...
希望这会有所帮助!
这篇关于滚动时编辑Div(例如在Google文档中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!