JavaScript實現側邊廣告效果

用JavaScript實現了一個小效果:滑動頁面,側邊廣告一起滑動一定距離,返回原來位置。

HTML:

<div id="aside">
        <img src="./images/float.jpg" alt="">
 </div>
 <div class="main">
    <p>加油!</p>
    <p>最棒!</p>
    <p>加油!</p>
    <p>最棒!</p>
    <p>加油!</p>
    <p>最棒!</p>
    <p>加油!</p>
    <p>最棒!</p>
</div>

css:

    *{
               margin:0;
           padding:0;
           list-style: none;
           border:none;
       }
       #aside{
           width:150px;
           position: absolute;
           top:100px;
           left:0;
       }
       #aside img{
           width:100%;
       }
       .main p{
           text-align: center;
           line-height: 250px;
           font-size: 20px;
           height: 250px;
           width:100%;
       }
       .main p:nth-child(even){
           background-color: #ddfafa;
       }
       .main p:nth-child(odd){
           background-color: #d5a6f0;
       }

JavaScript:

window.οnlοad=function(){
    //1 獲取廣告頭部
    var offset_top=$("aside").offsetTop;
    //2 監聽窗口滾動
    var begin=0,end =0,timer=null;   
    window.οnscrοll=function(){
        //2.0 清除定時器(在事件開始前清除)
        clearInterval(timer);
        //2.1 獲取滾動高度
        var scroll_top=scroll().top;
        end=offset_top+scroll_top;

        //2.2 緩動動畫
        timer=setInterval(function(){
            begin=begin+(end - begin)*0.2;
            $("aside").style.top=begin+"px";
            //清除定時器
            if(Math.round(begin)===end){
                clearInterval(timer);
            }

        },20);
    }
}

function scroll() {
    if(window.pageYOffset !== null){
        return {
            top: window.pageYOffset,
            left: window.pageXOffset
        }
    }else if(document.compatMode === "CSS1Compat"){ // W3C
        return {
            top: document.documentElement.scrollTop,
            left: document.documentElement.scrollLeft
        }
    }

    return {
        top: document.body.scrollTop,
        left: document.body.scrollLeft
    }
}

function $(id) {
    return typeof id === "string" ? document.getElementById(id) : null;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章