很多网页都有这样的效果,比如篇幅较长的网页,能够实现侧栏的某个某块固定效果,但是这个模块并不是一开始就是固定的,而是当它移动的指定位置之后才会固定,下面就通过代码实例介绍一下如何实现此效果。

代码如下:
   [ 其他 ] 运行代码    下载代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="https://www.51qianduan.com/" />
<title>51前端</title>
<style type="text/css">
body{
  width:900px;
  margin:0px auto;
  line-height:23px;
  padding:10px;
}
#right{
  float:right; 
  width:750px;
  border:solid 1px gray;
  padding:10px;
  height:1000px;
}
#fix{
  border:solid 1px gray; 
  width:90px;
  padding:10px;
  background-color:#eff;
  height:150px;
}
#top{
  width:92px;
  padding:10px;
  height:100px;
  background:red;
}
</style>
<script type="text/javascript">
window.onload=function(){
  function htmlPosition(obj){
    var o=obj;
    var t=o.offsetTop;
    var l=o.offsetLeft;
    while(o=o.offsetParent){
      t += o.offsetTop;
      l += o.offsetLeft;
    }
    obj.data_top = t;
    obj.data_left = l;
  }
    
  function htmlScroll(){
    var top=document.body.scrollTop||document.documentElement.scrollTop;
    if(elFix.data_top<top){
      elFix.style.position='fixed';
      elFix.style.top=0;
      elFix.style.left=elFix.data_left;
    }
    else{
      elFix.style.position='static';
    }
  }
    
  var oldHtmlWidth=document.documentElement.offsetWidth;
  window.onresize=function(){
    var newHtmlWidth=document.documentElement.offsetWidth;
    if(oldHtmlWidth == newHtmlWidth){
      return;
    }
    oldHtmlWidth = newHtmlWidth;
    elFix.style.position = 'static';
    htmlPosition(elFix);
    htmlScroll();
  }
  var elFix=document.getElementById('fix');
  htmlPosition(elFix);
  window.onscroll=htmlScroll;
}
</script>
</head>
<body>
<div>
  <div style="float:left;width:120px; ">
    <div id="top"></div>
    <div id="fix"></div>
  </div>
  <div id="right"></div>
</div>
</body>
</html>

代码描述:js元素 滚动指定位置 实现固定。js元素滚动指定位置实现固定效果源码下载



125 167



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到