1. 程式人生 > >為網頁新增蒙板效果和彈出層js

為網頁新增蒙板效果和彈出層js

   有的時候我們需要實現彈出一個層然後下面的層被一層蒙板蒙起來使使用者不能點選裡面的按鈕效果,這一效果具體實現的程式碼如下:這是一個測試效果用的html,可以直接拷貝到html檔案中執行。

<html>
<head>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script type="text/javascript">
//獲得座標
        function getPosition() {
            var top = document.documentElement.scrollTop;
            var left = document.documentElement.scrollLeft;
            var height = document.documentElement.clientHeight;
            var width = document.documentElement.clientWidth;
            //top=500;
            left = 200;
            //height=0;
            width = 500;
            height=300;
            top=200;
            return { top: top, left: left, height: height, width: width };
        }
        //遮蔽輸入,顯示蒙板
        function showMask(id) {
            var obj = document.getElementById(id);
            obj.style.width = document.body.clientWidth;
            obj.style.height = document.body.clientHeight;
            obj.style.display = "block";
        }
        //隱藏蒙板
        function hideMask(id) {
            document.getElementById(id).style.display = "none";
        }
        //顯示登入
        function showPop(id) {
            showMask('mask');
            var width = 300;  //彈出框的寬度
            var height = 170;  //彈出框的高度
            var obj = document.getElementById(id);
            obj.style.display = "block";
            obj.style.position = "absolute";
            obj.style.zindex = "10";
            obj.style.overflow = "hidden";
            obj.style.width = width + "px";
            obj.style.height = height + "px";
            var Position = getPosition();
            leftadd = (Position.width - width) / 2;
            topadd = (Position.height - height) / 2;
            obj.style.top = (Position.top + topadd) + "px";
            obj.style.left = (Position.left + leftadd) + "px";
            window.onscroll = function() {
                var Position = getPosition();
                obj.style.top = (Position.top + topadd) + "px";
                obj.style.left = (Position.left + leftadd) + "px";
            };
            
        }
        //隱含
        function hidePop(id) {
        hideMask('mask');
            document.getElementById(id).style.display = "none";
        }
</script>
</head>

<body>
<div>
<input type="button" value="測試彈出層" onclick="showPop('tcc')"/>
</div>

<!--蒙板-->
        <div id="mask" style="filter: Alpha(opacity=30); -moz-opacity: 0.3; -khtml-opacity: 0.3;
            opacity: 0.3; background-color: #000; width: 100%; height: 100%; z-index: 5px;
            position: absolute; left: 0; top: 0; display: none; overflow: hidden;">
        </div>
        <!--蒙板結束-->
        <!--彈出層---->
        <div id="tcc" style="display:none;background-color:#00ffff;">
        <input type="button" id="test" value="隱藏彈出層" onclick="hidePop('tcc');"/>
        </div>
        
        
</body>

</html>