30行js搞定js弹div,支持右下弹出div层,左下弹出div层,右上弹出div层,左上弹出div层,定时关闭

先看一下效果图:

代码如下:

<html>
<head>
    <script type="text/javascript">
        function popshow(msg, options) {
            var ops = Object.assign({
                time: 3000//默认3秒关闭,=0需要手动关闭
                ,site: 1//弹出位置:1右下,2左下,3左上,4右上
                , color: 'green'//默认颜色:green,还可支持blue,red,orange 或任意16进颜色代码
            }, options);
            if (document.getElementById("popshowDiv" + ops.site) == null) {
                var siteStyle = "bottom: 5px; right: 5px;"
                switch (ops.site) {
                    case 2: siteStyle = "bottom: 5px; left: 5px;"; break;
                    case 3: siteStyle = "top: 5px; left: 5px;";break;
                    case 4: siteStyle = "top: 5px; right: 5px;";break;
                }
                var popshowDiv = document.createElement("div");
                popshowDiv.style.cssText = 'position: fixed; 400px; height: auto; z-index:100; padding: 5px; font-size: 13px;'+siteStyle;
                popshowDiv.id = "popshowDiv"+ ops.site;
                document.body.appendChild(popshowDiv);
            }            
            var showDiv = document.createElement("div");
            showDiv.setAttribute("style", 'position: relative; margin-bottom: 5px; padding: 5px; opacity:1; transition: all .5s ease-out; cursor: pointer;color:#66c546; border:2px solid ' + ops.color + ";color:" + ops.color);
            showDiv.innerHTML = msg;
            var closeDiv = document.createElement("div");
            closeDiv.setAttribute("style", "position: absolute; right: 5px; top:4px; cursor: pointer;opacity:1; transition: none;color:" + ops.color);
            closeDiv.innerHTML = "x";
            closeDiv.onclick = function () { document.getElementById("popshowDiv"+ ops.site).removeChild(showDiv); }
            showDiv.appendChild(closeDiv)
            document.getElementById("popshowDiv"+ ops.site).appendChild(showDiv);
            if (ops.time >0) {setTimeout(function () { document.getElementById("popshowDiv"+ ops.site).removeChild(showDiv); }, ops.time)}
        }
    </script>
</head>

<body>
    <br /><br /><br />
    <input type="button" value="右下(默认)" onclick="popshow('右下(默认)右下(默认)右下(默认)右下(默认)右下(默认3秒后自动关闭) ')" />
    <input type="button" value="左下" onclick="popshow('左下信息10秒后关闭:{site:1,time:10000}', {site:2,time:10000,color:'red'})" /><!-- 10秒 -->
    <input type="button" value="左上" onclick="popshow('左上信息需要手动关闭:{site:2,time:0}', {site:3,time:0,color:'blue'})" />
    <input type="button" value="右上" onclick="popshow('左上信息Test', {site:4,time:0,color:'orange'})" />
</body>
</html>
原文地址:https://www.cnblogs.com/q149072205/p/14248017.html