css+js定位到屏幕中間


ex:讓一個div始終顯示在屏幕中間

一、

css:#idName{position: absolute;z-index: 999;width: ?px;margin-top: ?px;}//此處的初始定位按具體的自己調

計算並設置頁面滾動條改變時移動的距離:

function sc1(idName) {
    var d = document.getElementById(idName);
    d.style.top = (document.documentElement.scrollTop + (document.documentElement.clientHeight - d.offsetHeight) / 2) 【此處加上或減去上移或者下移的高度】+ "px";
    d.style.left = (document.documentElement.scrollLeft + (document.documentElement.clientWidth - d.offsetWidth) / 2) + "px";
}

 

    function scall() {
        sc1("idName");
        }

            window.onscroll = scall;
            window.onresize = scall;
            window.onload = scall;

 

若是和diaplay一起使用  在顯示后再調用             

            window.onscroll = scall;
            window.onresize = scall;

 二、純css實現始終顯示在屏幕中間

ex:

#div_window {
    width: 400px; /**寬度**/
    height: 300px; /**高度**/
    position: fixed; /**定位采用此種方式**/
    left: 50%; /**左邊50%**/
    top: 50%; /**頂部50%**/
    margin-top: -100px; /**上移-50%**/
    margin-left: -150px; /**左移-50%**/
    display: none;
    border: 1px black solid;
    background-color: #DCDCDC;
}

樣式和寬高自己定,根據寬高調整margin-top,margin-left  將它調到頁面中間即可。滾動時便會根據位置顯示在屏幕中間。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM