jquery实现固定滚动特效
<head>
<meta charset="UTF-8"><title>jquery实现固定右侧边栏滚动特效</title>
<style>
#slide-scroll{
float: left;
width:70%;
background: palegreen;
height: 2000px;
}
#slide-fixed{
float: right;
width:30%;
background: plum;
height: 1000px;
}
</style>
</head>
<body>
<div id="slide-scroll" ></div>
<div id="slide-fixed"></div>
</body>
<script src="https://code.jquery.com/jquery.js"></script>
<script>
var jWindow=$(window);//缓存window对象
jWindow.scroll(function(){//监听window滚动事件
var scrollHeight=jWindow.scrollTop();//滚动高度
var screenHeight=jWindow.height();//window可见区域高度
var slideHeight=$("#slide-fixed").height();//右侧边栏高度
if(scrollHeight+screenHeight>slideHeight){
$("#slide-fixed").css({
"position":"fixed",
"right":0,
"top":-(slideHeight-screenHeight)+"px"
});
}else{
$("#slide-fixed").css({
"position":"static"
});
}
});
window.οnlοad=function(){//触发window滚动监听事件
jWindow.trigger("scroll");
};
jWindow.resize(function(){//触发window滚动监听事件
jWindow.trigger("scroll");
});
</script>
js实现固定滚动特效
<head>
<meta charset="UTF-8">
<title>javascript实现固定右侧边栏滚动特效</title>
<style>
#slide-scroll{
float: left;
width:70%;
background: palegreen;
height: 2000px;
}
#slide-fixed{
float: right;
width:30%;
background: plum;
height: 1000px;
}
</style>
</head>
<body>
<div id="slide-scroll" ></div>
<div id="slide-fixed"></div>
</body>
<script>
/*获取元素的dom引用*/
var $ = function(id){
return document.getElementById(id);
}
/*事件绑定函数*/
var addEvent = function(obj,event,fn){
if(obj.addEventListener){/*w3c标准方法*/
obj.addEventListener(event,fn,false);//非ie浏览器事件模型有2中,捕获事件,冒泡事件(默认false,ie浏览器只支持冒泡模型)
}else if(obj.attachEvent){//ie浏览器
obj.attachEvent("on"+event,fn);//ie浏览器只支持冒泡模型
}
}
var sideDom=$("slide-fixed");
var scrollEvent=function(){
var sideHeight=sideDom.offsetHeight;
var screenHeight=document.documentElement.clientHeight||document.body.clientHeight;
var scrollHeight=document.documentElement.scrollTop||document.body.scrollTop;
if(scrollHeight+screenHeight>sideHeight){
sideDom.style.cssText="position:fixed;right:0px;top:"+(screenHeight-sideHeight)+"px";
}else{
sideDom.style.position="static";
}
}
addEvent(window,"scroll",function(){
scrollEvent();
});
addEvent(window,"resize",function(){
scrollEvent();
})
</script>