效果
关键
text-shadow
样式为标准CSS3样式,用于添加一个或多个文字阴影,用于其的语法格式为:
text-shadow: h-shadow v-shadow blur color
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Shadow</title>
</head>
<body>
<div class="hero">
<h1 contenteditable>🔱GIAO GIAO🔕</h1>
</div>
<style>
html {
color: black;
font-family: sans-serif;
}
body {
margin: 0;
}
.hero {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
color: black;
}
h1 {
text-shadow: 10px 10px 0 rgba(0, 0, 0, 1);
font-size: 100px;
}
</style>
<script>
let hero = document.querySelector('.hero');
let text = hero.querySelector('h1');
let factor = 0.4;//当鼠标移动至显示区域边界时,阴影距离占hero元素宽和高的比例
hero.addEventListener('mousemove', shadowMove);
function shadowMove(e) {
// 事件发生的event对象中获取需要的值:
// range指代hero元素的宽和高
var range = {
x: hero.offsetWidth,
y: hero.offsetHeight
}
// pos表示鼠标当前位置的坐标
var pos = {
x: e.target.offsetLeft + e.offsetX,
y: e.target.offsetTop + e.offsetY
}
//计算阴影移动距离
var disX = parseInt((pos.x - range.x / 2) * factor);
var disY = parseInt((pos.y - range.y / 2) * factor);
text.style.textShadow = `
${disX}px ${disY}px 0 rgba(255,0,255,0.7),
${disX * -1}px ${disY}px 0 rgba(0,255,255,0.7),
${disY}px ${disX * -1}px 0 rgba(0,255,0,0.7),
${disY * -1}px ${disX}px 0 rgba(0,0,255,0.7)
`;
}
</script>
</body>
</html>