|
|
1
Temani Afif
6 年前
不要使用透明颜色的渐变。只使用纯色并控制
background-size
然后简单地做
img
阻止元素以避免空白问题:
不确定是否可以不使用包装器,因为您需要一个元素来应用渐变:
const wrapped = document.querySelector("#wrapped");
const img = wrapped.querySelector("img");
const box = img.getBoundingClientRect();
//wrapped.style.height = (box.bottom-box.top)+"px";
const bg = "linear-gradient(rgba(0,38,114,1),rgba(0,38,114,1))";
console.log(wrapped);
wrapped.addEventListener("mousemove", (e)=>{
const box = wrapped.getBoundingClientRect();
const mousePos = e.clientX - box.left;
const max = box.right-box.left;
const perc = 100*(mousePos/max);
//console.log(gradient);
///console.log(perc);
wrapped.style.backgroundSize =perc+"% 100%";
wrapped.style.color = "red";
}, {capture: false});
#wrapped {
display: inline-block;
margin: 0px;
/*padding: -1px; there is no negative padding */
border-width: 1px;
border-color:transparent;
border-style: solid;
background-position:left;
background-repeat: no-repeat;
}
#wrapped img {
display:block;
}
#wrapped:hover img {
opacity: 0.3;
}
#wrapped:hover {
/*border-color:#002672;*/
background-image:linear-gradient(rgba(0,38,114,1),rgba(0,38,114,1));
background-size: 50% 100%;
}
<span id="wrapped"><img src="https://i.stack.imgur.com/lymku.png" /></span>
但是,您可能会考虑一个具有多个背景的想法,以避免出现图像,并且在结尾处有一个元素将替换图像:
const wrapped = document.querySelector("#wrapped");
wrapped.addEventListener("mousemove", (e)=>{
const box = wrapped.getBoundingClientRect();
const mousePos = e.clientX - box.left;
const max = box.right-box.left;
const perc = 100*(mousePos/max);
wrapped.style.backgroundSize =perc+"% 100%, 60% 100%";
}, {capture: false});
#wrapped {
display: inline-block;
border-width: 1px;
border-style: solid;
border-color:rgba(0,38,114,1);
height:10px;
width:100px;
background-image:
linear-gradient(transparent,transparent),
linear-gradient(rgba(0,38,114,1),rgba(0,38,114,1));
background-size: 60% 100%;
background-position:left;
background-repeat: no-repeat;
}
#wrapped:hover {
border-color:rgba(0,38,114,0.5);
background-image:
linear-gradient(rgba(0,38,114,1),rgba(0,38,114,1)),
linear-gradient(rgba(0,38,114,0.5),rgba(0,38,114,0.5));
}
<span id="wrapped"></span>
|