js显示和隐藏动画及鼠标穿透实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.button {
display: inline-block;
padding: 10px 20px;
background-color: #3498db;
color: #fff;
text-align: center;
text-decoration: none;
font-size: 16px;
}
#demo{
width: 200px;
height: 300px;
background: #ccc;
transition: opacity 0.5s ease;
opacity: 1;
position: absolute;
top: 50px;
left: 8px;
/*pointer-events: none;*/
}
</style>
<title>CSS Transition Example</title>
</head>
<body>
<a href="javascript:toggle()" class="button">toggle</a>
<div id="demo">
<div>aaaaaa</div>
<div>aaaaaa</div>
<div>aaaaaa</div>
</div>
<div>
<div>bbbbbb</div>
<div>bbbbbb</div>
<div>bbbbbb</div>
</div>
<script>
// 推荐
//使用 pointer-events: none; 允许鼠标穿透
function toggle2() {
const demo = document.querySelector("#demo");
const style = getComputedStyle(demo, null);
const opacity = +style.opacity === 1 ? 0 : 1;
demo.style.opacity = opacity;
if(opacity === 1) {
// 阻止鼠标穿透
demo.style.pointerEvents = 'auto';
} else {
// 允许鼠标穿透
demo.style.pointerEvents = 'none';
}
}
// 老旧浏览器模拟效果
let hasListend = false
function toggle() {
const demo = document.querySelector("#demo");
const style = getComputedStyle(demo, null);
if(style.display === 'none') demo.style.display = 'block';
const opacity = +style.opacity === 1 ? 0 : 1;
demo.style.opacity = opacity;
// 这里也可以使用setTimeout()简单实现
if(!hasListend) {
hasListend = true;
document.querySelector("#demo").addEventListener('transitionend', function(event) {
const opacity = +getComputedStyle(event.target, null).opacity;
if(opacity === 1) {
event.target.style.display = 'block';
} else {
event.target.style.display = 'none';
}
});
}
}
</script>
</body>
</html>