数据来源:ChatGPT

今天,我们来看一个鼠标悬停出现图片放大镜效果,这是一个比较实用且炫酷的纯CSS和JS实现的页面效果。

HTML

HTML代码非常简单,我们只需要一个div容器,内部嵌入一张图片,再添加一个用来显示放大镜的div元素。

CSS

CSS代码是实现放大镜效果的重要部分,我们需要设置容器、图片、放大镜的样式。同时,使用CSS的:hover伪类,控制鼠标悬停时的样式变化。

.container {position: relative;width: 200px;height: 300px;}.container img {width: 100%;height: 100%;object-fit: cover;}.magnifier {position: absolute;width: 120px;height: 120px;border: 3px solid #fff;border-radius: 60px;background-repeat: no-repeat;background-size: 400% 400%;z-index: 10;}.container:hover img {transform: scale(1.2);}.container:hover .magnifier {background-image: url(https://picsum.photos/id/237/800/1200);background-position: center;background-size: cover;top: -30px;left: calc(50% - 60px);transition: all 0.3s ease;}.hide {display: none;}

JS

最后,在JS代码中,我们监听container容器的mousemove和mouseleave事件,根据鼠标在容器上的位置,实现放大镜的效果。

const container = document.querySelector('.container');const magnifier = document.querySelector('.magnifier');container.addEventListener('mousemove', e => {magnifier.classList.remove('hide');const { left: containerX, top: containerY } = container.getBoundingClientRect();const x = e.pageX - containerX;const y = e.pageY - containerY;magnifier.style.backgroundPosition = `-${x * 2}px -${y * 2}px`;magnifier.style.left = `${x - 60}px`;magnifier.style.top = `${y - 60}px`;});container.addEventListener('mouseleave', () => {magnifier.classList.add('hide');});

当鼠标在容器上移动时,计算鼠标在容器上的位置(x,y),并将放大镜样式修改为对应位置上的图片所显示的区域。为了更好地实现放大镜的效果,我们需要用CSS实现放大镜区域。

最后,为了更好地表现界面效果,我们添加了过渡效果,使界面呈现更加平滑。

这样就完成了这个实用的页面效果。通过纯CSS和JS的实现,我们可以实现更加灵活的交互效果,同时还可以方便地应用于网页中,增加了用户体验感。

总的来说,通过这个案例,我们不仅了解了如何使用纯CSS和JS实现鼠标悬停出现图片放大镜效果,还理解了如何通过CSS的:hover伪类,控制样式变化,如何使用JS监听鼠标移动事件,在容器中实现放大镜效果,并且过渡效果可以使我们的页面效果展示的更加平滑。

如果我们需要在设计中展示具有实用价值和炫酷效果的UI交互,这个鼠标悬停出现图片放大镜效果是一个非常不错的选择,同时也更加符合人们对于高质量用户体验的追求。

完整代码

3D立方体切换动画.container {position: relative;width: 200px;height: 300px;}.container img {width: 100%;height: 100%;object-fit: cover;}/* 放大镜 */.magnifier {position: absolute;width: 120px;height: 120px;border: 3px solid #fff;border-radius: 60px;background-repeat: no-repeat;background-size: 400% 400%;z-index: 10;}/* 图片悬停时的样式 */.container:hover img {transform: scale(1.2);}.container:hover .magnifier {background-image: url(https://picsum.photos/id/237/800/1200);background-position: center;background-size: cover;top: -30px;left: calc(50% - 60px);transition: all 0.3s ease;}/* 隐藏放大镜 */.hide {display: none;}const container = document.querySelector('.container');const magnifier = document.querySelector('.magnifier');container.addEventListener('mousemove', e => {magnifier.classList.remove('hide');const { left: containerX, top: containerY } = container.getBoundingClientRect();const x = e.pageX - containerX;const y = e.pageY - containerY;magnifier.style.backgroundPosition = `-${x * 2}px -${y * 2}px`;magnifier.style.left = `${x - 60}px`;magnifier.style.top = `${y - 60}px`;});container.addEventListener('mouseleave', () => {magnifier.classList.add('hide');});

效果图