效果演示
制作思路
CSS 的mask
属性用于控制元素的可见区域,通过图像或渐变的透明度来隐藏或显示部分内容。元素的每个像素根据遮罩的对应像素的透明度决定显示程度。遮罩中完全透明的区域会隐藏元素内容,不透明区域则保留内容,半透明区域会呈现渐变效果。
那么我们可以将两张图片叠在一起,制作一个线性渐变区域控制mask
,让左边的图片从左往右不透明度从1变成0,右边的图片从左往右不透明度从0变成1,具体在哪个位置发生变化由input range
控制。
.before { position: absolute; width: 100%; height: 100%; mask: linear-gradient(to right, #000 0, var(--pos, 50%), #0000 0); }
.after { position: absolute; width: 100%; height: 100%; mask: linear-gradient(to right, #0000 0, var(--pos, 50%), #000 0); }
|
#range { position: absolute; vertical-align: middle; background: transparent; appearance: none; //想要自定义thumb,需要设置appearance: none width: 100%; z-index: 1; height: 100%; cursor: pointer }
//-webkit-slider-thumb和-moz-range-thumb是修改thumb的兼容写法 input[type="range"]::-webkit-slider-thumb { appearance: none; //想要自定义thumb,需要设置appearance: none width: 6px; height: 100%; background: black; border-radius: 3px; }
input[type="range"]::-moz-range-thumb { appearance: none; //想要自定义thumb,需要设置appearance: none width: 6px; height: 100%; background: black; border-radius: 3px; }
|
let rangePicker = document.getElementById('range')
function updateRangeValue() { document.documentElement.style.setProperty('--pos', `${rangePicker.value}%`); }
rangePicker.addEventListener('input', updateRangeValue)
|