为元素实现智能浮动

最近想要改造一下囧客圈
为长文章的侧边栏加入只能浮动的div.
在网上找到了几种解决办法:

0.显示要加载一下jq库,随便选,国外有用户就用google的,国内有用户就用百度或者新浪的.

1.

    <script type="text/javascript">
       $(function() {
           var offset = $("#text-3").offset();
           var topPadding = 15;
           $(window).scroll(function() {
               if ($(window).scrollTop() > offset.top) {
                   $("#text-3").stop().animate({
                       marginTop: $(window).scrollTop() - offset.top + topPadding
                   });
               } else {
                   $("#text-3").stop().animate({
                       marginTop: 0
                   });
               };
           });
       });
   </script>

2.

$.fn.smartFloat = function() {
    var position = function(element) {
        var top = element.position().top, pos = element.css("position");
        $(window).scroll(function() {
            var scrolls = $(this).scrollTop();
            if (scrolls > top) {
                if (window.XMLHttpRequest) {
                    element.css({
                        position: "fixed",
                        top: 0
                    });
                } else {
                    element.css({
                        top: scrolls
                    });
                }
            }else {
                element.css({
                    position: "absolute",
                    top: top
                });
            }
        });
    };
    return $(this).each(function() {
        position($(this));
    });
};

    $("#float").smartFloat();

3.
js:

    (function(){
    var oDiv=document.getElementById("float");
    var H=0,iE6;
    var Y=oDiv;
    while(Y){H+=Y.offsetTop;Y=Y.offsetParent};
    iE6=window.ActiveXObject&&!window.XMLHttpRequest;
    if(!iE6){
        window.onscroll=function()
        {
            var s=document.body.scrollTop||document.documentElement.scrollTop;
            if(s>H){oDiv.className="div1 div2";if(iE6){oDiv.style.top=(s-H)+"px";}}
            else{oDiv.className="div1";}    
        };
    }
})();

html:

<div id="box">
    <div id="float" class="div1">
        //随滚动移动的部分代码
    </div>
</div>

css:

#box{float:left;position:relative;width:295px;}
.div1{}
.div2{position:fixed;_position:absolute;top:3px;z-index:295;}
Share

小 虾

哦也,我是小虾

You may also like...

1 Response

  1. 我要发芽 says:

    不懂代码,唉。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.