CSS篇之炫酷框
加上背景之后就是下图:
实现原理:div大小为20px 20px;那么伪元素大小要比div大出一圈,才能显示出边框;
在鼠标滑过的时候,动态更改伪元素的背景色位置
<div id="b" class="b"></div>
*{
--border: 4px;
border:none;
}
.b{
width:200px;
height:200px;
border:1px solid black;
box-sizing:border-box;
position: relative;
background:#999;
}
.b::after {
content: "";
display: block;
width: calc(100% + var(--border) * 2);
height: calc(100% + var(--border) * 2);
position: absolute;
z-index: -1;
background-image: var(--bg);
left:calc(var(--border) * -1);
top:calc(var(--border) * -1);
}
const b=document.getElementById('b');
b.addEventListener("mousemove", e=>{
let rect = b.getBoundingClientRect();
let x = e.pageX - rect.left;
let y = e.pageY - rect.top;
b.style.setProperty(
"--bg",
`radial-gradient(100px at ${x}px ${y}px, rgba(186, 10, 244, 0.5), rgba(255, 255, 255, 0))`
);
})
上面是一个dom情况,如果多个dom,可遍历dom,更改radial-gradient属性;一下是多个dom的效果展示:
多个dom的遍历代码:
window.addEventListener("mousemove", (e) => {
let bt = document.querySelectorAll(".b");
for (let i = 0; i < bt.length; i++) {
let rect = bt[i].getBoundingClientRect();
let x = e.pageX - rect.left;
let y = e.pageY - rect.top;
bt[i].style.setProperty(
"--afterBack",
`radial-gradient(100px at ${x}px ${y}px, rgba(186, 10, 244, 0.5), rgba(255, 255, 255, 0))`
);
}
});