js 如何自己封装一个 弹窗功能?

作者站长头像
站长
· 阅读数 7

js 如何自己封装一个 弹窗功能?

回复
1个回答
avatar
test
2024-06-30

没懂你想要啥样的,自己改改

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .popup {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .popup-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: white;
        padding: 20px;
        border-radius: 5px;
    }
</style>

<body>
    <div id="myPopup" class="popup">
        <div class="popup-content">
            <span id="popup-message"></span>
            <button id="popup-close">关闭</button>
        </div>
    </div>
    <button id="popup-open">打开弹窗</button>
</body>

</html>
<script>
    function showPopup(message) {
        var popup = document.getElementById('myPopup');
        var messageSpan = document.getElementById('popup-message');

        messageSpan.textContent = message;
        popup.style.display = 'block';
    }

    function hidePopup() {
        var popup = document.getElementById('myPopup');
        popup.style.display = 'none';
    }

    var closeButton = document.getElementById('popup-close');
    closeButton.addEventListener('click', hidePopup);

    var openButton = document.getElementById('popup-open');
    openButton.addEventListener('click', () => showPopup('asdad'));

</script>
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容