类似antdesign modal效果
https://ant.design/components/modal-cn/
核心
popup.style.cssText =
`transform-origin: ${leftBtn.getBoundingClientRect().x - window.innerWidth / 2}px ${leftBtn.getBoundingClientRect().y - window.innerHeight / 2}px`;
因为我的弹窗默认在屏幕中间,所以要减去屏幕宽高的一半,如果默认在左上角则不用减了,直接就是鼠标点击位置就行了。
transform-origin
设置transform-origin
第一个参数为
鼠标点击的位置的x轴坐标 - 屏幕宽度 / 2
第二个参数为 1
y轴坐标 - 屏幕高度 / 2
完整demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.popup {
width: 600px;
height: 400px;
position: fixed;
left: 50%;
top: 50%;
transition: all 0.28s;
transform: scale(0) translate(-50%, -50%);
background-color: burlywood;
z-index: 2;
}
.popup_show {
transition: all 0.28s;
transform: scale(1) translate(-50%, -50%);
}
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
}
.mask_show {
display: block;
}
</style>
</head>
<body>
<div>
<button style="float: right;" id="left-btn">
click me
</button>
<div id="mask" class="mask"></div>
<div id="popup" class="popup">
</div>
</div>
<script>
window.onload = function () {
const $ = (el) => document.querySelector(el)
const leftBtn = $("#left-btn")
, popup = $("#popup")
, mask = $("#mask")
// 初始化第一次的transform-origin位置
popup.style.cssText =
`transform-origin: ${leftBtn.getBoundingClientRect().x - window.innerWidth / 2}px ${leftBtn.getBoundingClientRect().y - window.innerHeight / 2}px`;
// 点击按钮出现弹窗
leftBtn.addEventListener('click', (e) => {
popup.style.cssText =
`transform-origin: ${e.x - window.innerWidth / 2}px ${e.y - window.innerHeight / 2}px`;
popup.classList.add('popup_show')
mask.classList.add('mask_show')
})
// 点击遮罩关闭弹窗
mask.addEventListener('click', () => {
popup.classList.remove('popup_show')
mask.classList.remove('mask_show')
})
}
</script>
</body>
</html>