请写一个html点击文字弹出div弹窗的代码要求要有设置弹窗宽度和高度的并且要求不管宽度和高度有多大都要自适应居中垂直水平居中的代码。请注意宽度和高度为100占满整个页面另外如果后期要修改宽度和高度不管怎么改宽度和高度都要垂直水平居中
以下是满足您要求的HTML代码:
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f1f1f1;
}
.popup {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.5);
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s;
}
.popup-content {
max-width: 100%;
max-height: 100%;
padding: 20px;
background-color: white;
text-align: center;
overflow: auto;
}
.show-popup {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body>
<p>点击下方文字弹出弹窗:</p>
<p><a href="#" onclick="togglePopup()">点击这里</a></p>
<div id="popup" class="popup">
<div class="popup-content">
<h1>这是一个弹窗</h1>
<p>弹窗的内容可以根据需求进行修改</p>
<button onclick="togglePopup()">关闭</button>
</div>
</div>
<script>
function togglePopup() {
var popup = document.getElementById("popup");
popup.classList.toggle("show-popup");
}
</script>
</body>
</html>
这个代码中,当点击“点击这里”文字时,会触发togglePopup()函数,该函数会通过修改弹窗的CSS类名来切换弹窗的显示和隐藏。弹窗的样式使用CSS中的position: absolute和Flex布局来实现水平和垂直居中。弹窗的宽度和高度使用max-width和max-height设置为100%,并且使用overflow: auto来实现内容超出弹窗时的滚动。背景使用半透明的黑色来实现遮罩效果。
原文地址: https://www.cveoy.top/t/topic/i7nK 著作权归作者所有。请勿转载和采集!