哔哩哔哩秋季版图实现镜头景深效果
源代码转自b站up主CodingStartup起码课 https://www.
HTML
<header>
<div><img src="https://assets.
<div><img src="https://assets.
<div><img src="https://assets.
<div><img src="https://assets.
<div><img src="https://assets.
<div><img src="https://assets.
</header>
CSS
body {
margin: 0;
}
header {
height: 160px;
position: relative;
overflow: hidden;
}
header > div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
--offset: 0px;
--blur: 2px;
}
header > div > img {
display: block;
width: 110%;
height: 100%;
object-fit: cover;
transform: translatex(var(--offset));
filter: blur(var(--blur));
}
JavaScript
const images = document.querySelectorAll('header > div > img')
document.querySelector('header').addEventListener('mousemove', (e) => {
let percentage = e.clientX / window.outerWidth
let offset = 10 * percentage
let blur = 20
for (let [index, image] of images.entries()) {
offset *= 1.3
let blurValue = (Math.pow((index / images.length - percentage), 2) * blur)
image.style.setProperty('--offset', `${offset}px`)
image.style.setProperty('--blur', `${blurValue}px`)
}
})