最近想仿照淘宝首页的侧边栏,写个简单的小例子。获取滚动条距离顶部的距离 用到了window.pageYOffset 方法。
window.pageYOffset
返回文档当前沿垂直轴(即向上或向下)滚动的像素数,其值为0.0,表示该Document的顶部边缘当前与窗口内容区域的顶部边缘对齐。 pageYOffset是scrollY的一个别名是 window的只读属性
在IE9及以上、谷歌 、Safari、firefox,Opera(presto内核) 都支持 此语句
window.pageYOffset
那在IE低版本上怎么获取呢?
document.documentElement.scrollTop;
下面个实例吧:仿照淘宝侧边栏的效果
<div id="head-top">
<ul>
<li>登录</li>
<li>注册</li>
</ul>
</div>
<div id="content">
<div id="header"></div>
<div id="bodyer"></div>
<div id="footer"></div>
</div>
<div class="slider-bar">
<span class="goBack">回到顶部</span>
</div>
#header{
width: 100%;
height: 150px;
background: #FFB6C1
}
#bodyer{
width: 100%;
height: 1200px;
background: #BA55D3
}
#footer{
width: 100%;
height: 200px;
background: #4682B4
}
.slider-bar{
width: 40px;
height: 150px;
background: #800000;
position: absolute;
right: 50px;
top: 500px;
}
#head-top{
width: 100%;
height: 40px;
border-bottom: 2px solid #ccc;
position: fixed;
background: #FFF;
display: none;
}
#head-top ul li{
float: left;
padding: 0 20px;
}
.goBack{
display: none;
margin: 110px 0 0 0;
width: 40px;
height: 40px;
color: #fff;
text-align: center;
cursor: pointer;
}
var headTop = document.querySelector('#head-top');
var header = document.querySelector('#header');
var bodyer = document.querySelector('#bodyer');
var sliderBar = document.querySelector('.slider-bar');
var goBack = document.querySelector('.goBack');
//滚动到header看不见时 进行固定定位
var sliderBarTop = bodyerTop = bodyer.offsetTop;
//侧边栏顶部的距离 = sliderBar的距离 - bodyer距离顶部的距离时 出现:返回顶部
var sliderTop = sliderBar.offsetTop - bodyer.offsetTop;
document.addEventListener('scroll',function(){
//当文档向上滚动的距离大于等于sliderBarTop(bodyer.offsetTop)时就固定位置
if (window.pageYOffset >= bodyerTop) {
sliderBar.style.position = 'fixed';
sliderBar.style.top = sliderTop+ 'px';
headTop.style.display = "block";
}else{
sliderBar.style.position = 'absolute';
sliderBar.style.top = 500 + 'px';
headTop.style.display = "none";
goBack.style.display ="none";
}
window.pageYOffset >= sliderTop ? goBack.style.display ="block" : goBack.style.display ="none";
})
//点击回到顶部
goBack.onclick = function(){
console.log(document.documentElement.scrollTop = document.body.scrollTop =0);
}
思路:
页面监听事件 document.addEventListener();
当header看不见时:侧边栏固定在顶部不动,
当header看不见 --就是 bodyer距离顶部的距离 为零时:顶部出现小窄条,同时侧边栏固定在顶部不动将sliderBar固定定位。
offsetTop:当前元素顶端距离父元素顶端距离,鼠标滚轮不会影响其数值.
scrollTop:当前元素顶端距离窗口顶端距离,鼠标滚轮会影响其数值.
我的文章都是学习过程中的总结,如果发现错误,欢迎留言指出,我及时更正。