Javascript實現頁面內元素添加捲軸

來源:互聯網
上載者:User

無需多言,直接上代碼,高度超過時自動顯示捲軸,不超過高度時隱藏捲軸。

<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title><style>  article, aside, figure, footer, header, hgroup,   menu, nav, section { display: block; }</style></head><body><div id="divContainer" style="width:200px;overflow-y:auto; overflow-x:hidden; height:200px;border:0px solid red;">    <div id="divContent" style="width:200px;height:200px;border:0px solid black;">      <p>測試資料1</p>      <p>測試資料2</p>      <p>測試資料3</p>      <p>測試資料4</p>      <p>測試資料5</p>      <p>測試資料6</p>      <p>測試資料7</p>      <p>測試資料8</p>      <p>測試資料9</p>      <p>測試資料10</p>      <p>測試資料11</p>      <p>測試資料12</p>    </div></div><script type="text/javascript">window.onload = function(){     var nScrollHight = document.getElementById("divContent").offsetHeight; //滾動距離總長(注意不是捲軸的長度)    var nScrollTop = 0;   //滾動到的當前位置    var nDivHight = document.getElementById("divContainer").offsetHeight; //divContainer的高度        document.getElementById("divContainer").onscroll =function(){           nScrollTop = this.scrollTop;//0~250;        nScrollHight = this.scrollHeight;//750,1000;        if(nScrollTop + nDivHight >= nScrollHight)        {            document.getElementById("divContent").style.height=1000;            alert("Scroll to Bottom, ScrollTop is:" + nScrollTop);        }    }   }</script> </body></html>

Javascript用於檢測當前的滾動位置。如果只是顯示捲軸,則不需要Javascript代碼。

線上示範地址:http://jsbin.com/ulijos

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.