html任意区域滚动跟随代码.

html任意区域滚动跟随代码._第1张图片

网页滚动时, div也会跟随滚动. 功能适合于任何元素体中, 不仅仅是顶部滚动.

代码如下:
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8" />
	<meta http-equiv="content-type" content="text/html" />

	<title>无标题 2</title>
    <script type="text/javascript" src="./ecshop/js/mbs/jquery.min.1.71.js"></script>
    <style type="text/css">
    *{margin: 0px; padding: 0px;}
    </style>
    
    <script type="text/javascript">
        
    $(function (){
        div_offset_top('userreg_div','main_content',0);
    })
    
    function div_offset_top(idname,parentidname, offset_default){
            var this_offsettop,parent_h,this_h,offtop,margintop,parent_offsettop;
            this_h = $('#'+idname).height();
            this_offsettop = $('#'+idname).offset().top;
            margintop = parseInt($('#'+idname).css('margin-top'));
            
            parent_offsettop = $('#'+parentidname).offset().top;
            parent_h = $('#'+parentidname).height();
            
            if(margintop >= this_offsettop){
                max_offsetop = (parent_h-(this_h+parent_offsettop));
            }else{
                max_offsetop = (parent_h-(this_h+(this_offsettop-parent_offsettop)));
            }
            
            $(window).scroll(function (){
                offtop = $(this).scrollTop()+offset_default;
                if(margintop < this_offsettop) // 如果是margin-top 块, 就直接以拉长高度为top.
                    offtop = offtop-(this_offsettop);
                
                // 日志
                $('#'+idname).text('max:'+max_offsetop+' offtop: '+ offtop+' parent_h:'+parent_h+' div_height:'+(this_h+this_offsettop));
                if($(this).scrollTop() > this_offsettop){
                    if(max_offsetop > offtop)
                        $('#'+idname).css('margin-top',(offtop) +'px');
                }else{
                    $('#'+idname).css('margin-top','0px');
                }
            })
    }
        
    </script>
    
</head>


<body style="background-color: #8C9CEA;">
<div id="main_content" style="height:1800px; width: 400px; overflow: hidden;  background-color: #FF8040;">
    <div id="userreg_div" style="height: 30px;background-color: green; color: white;">html mess</div>
</div>
</body>
</html>

请自动替换自己的jquery路径.
div_offset_top(子元素id名, 父元素id名, 向上偏移量)
父元素id名 主要是用来计算最大可滚到多少px.

你可能感兴趣的:(html任意区域滚动跟随代码.)