21xrx.com
2024-09-20 05:27:56 Friday
登录
文章检索 我的文章 写文章
用JavaScript制作自定义弹窗嵌入到HTML中
2023-06-16 14:05:26 深夜i     --     --
JavaScript 弹窗 HTML

JavaScript是一种非常有用的编程语言,它可以为我们的网页添加交互和动态效果。其中一项常用的功能是弹窗。本文将向您展示如何使用JavaScript编写自定义弹窗,并将其嵌入到HTML中。

首先,我们需要创建一个HTML文档,并在其中添加一些内容,例如一个按钮。


JavaScript弹窗示例

接下来,在``标签中创建一个JavaScript函数,用于弹出自定义弹窗。


function showAlert() {

// 创建弹窗

var popup = document.createElement("div");

popup.classList.add("popup");

// 添加标题

var title = document.createElement("h2");

title.textContent = "这是一个弹窗";

popup.appendChild(title);

// 添加文本

var message = document.createElement("p");

message.textContent = "这是弹窗的内容。";

popup.appendChild(message);

// 添加“关闭”按钮

var closeButton = document.createElement("button");

closeButton.textContent = "关闭";

closeButton.onclick = function() {

popup.parentNode.removeChild(popup);

};

popup.appendChild(closeButton);

// 将弹窗添加到页面

document.body.appendChild(popup);

}

最后,我们需要为弹窗定义一些CSS样式。


.popup {

position: fixed;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

background-color: white;

padding: 20px;

border: 1px solid black;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);

}

.popup h2

margin-top: 0;

.popup button

margin-top: 20px;

现在我们可以检查一下页面并点击按钮,看看我们的弹窗是否符合预期了。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复