繁体   English   中英

悬停在图像上时,只显示光标所在的部分

[英]When hovering over image, only display the part where the cursor is over it

提前信息:
您可以在https://juek3y.com 上查看当前代码或现场演示(没有工作悬停图像)。

想法:
我希望,当我将光标(黑色圆圈)悬停在图像上时,只显示光标悬停在其上的图像的这一部分(而不是整个图像)。

问题:
我从哪里开始? 我见过一些与 Z-Index 一起使用的 CodePens。 但是,到目前为止,我还没有成功。 还有一个像这样的示例网站对我来说就足够了。


为了更好地理解,我还有两张示例图片。

在此处输入图片说明

在第一个图像中,较小的圆圈/光标(黑色/绿松石圆圈)悬停在圆形文本上,但尚未与图像相交。 因此这是隐藏的。


在此处输入图片说明
在第二张图片中,光标已经悬停在图片上方,这部分图片也显示出来了。

您可以将 CSS clip-path属性与mousemove侦听器结合使用以显示鼠标下方的正面图像,并在mouseleave上清除 clip-path 。

在叠加图像上使用 CSS反转过滤器的粗略工作片段。 您可以轻松添加事件委托来处理多个叠加层等。

 const overlay = document.querySelector('.overlay'); overlay.addEventListener('mousemove', e => { const {height, width} = e.currentTarget.getBoundingClientRect(); const x = e.offsetX; const y = e.offsetY; const xPercent = Math.round((x/width)*100); const yPercent = Math.round((y/height)*100); e.currentTarget.style.clipPath = `circle(18% at ${xPercent}% ${yPercent}%)`; }); overlay.addEventListener('mouseleave', e => { e.currentTarget.style.clipPath = null; });
 .container { position: relative; } .container img { width: 200px; height: 200px; position: absolute; top: 0; left: 0; } .overlay { filter: invert(var(--value, 100%)); clip-path: circle(0 at 49% 45%); }
 <div class='container'> <img src='https://source.unsplash.com/random' /> <img src='https://source.unsplash.com/random' class='overlay'/> </div>

您可以使用 CSS 掩码在元素中“挖一个洞”。

您可以将要(部分)作为背景显示到 div 的图像,然后用后伪元素覆盖它,该伪元素将您想要的图像作为背景放在前面,用径向渐变遮蔽,该渐变与鼠标位置。

此代码段将彩色图像与灰度图像叠加在一起,例如:

 window.onload = function() { const div = document.querySelector('.hole'); let isIn = false; div.addEventListener('mouseover', function() { isIn = true; }); div.addEventListener('mouseout', function() { isIn = false; }); div.addEventListener('mousemove', function() { if (isIn) { div.style.setProperty('--x', event.clientX + 'px'); div.style.setProperty('--y', event.clientY + 'px'); } }); }
 .hole { background-image: url(https://picsum.photos/id/1016/1024/768); background-size: cover; --x: 200px; --y: 150px; width: 100vw; height: 100vh; position: relative; } .hole::after { content: ''; width: 100%; height: 100%; position: absolute; top: 0; left: 0; background-image: url(https://picsum.photos/id/1016/1024/768?grayscale); background-size: cover; z-index: 1; -webkit-mask-repeat: no-repeat no-repeat; mask-repeat: no-repeat no-repeat; -webkit-mask-image: radial-gradient(200px at var(--x) var(--y), transparent 95%, black 100%); mask-image: radial-gradient(200px at var(--x) var(--y), transparent 95%, black 100%); }
 <div class="hole"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM