该效果是在逛https://www.jetbrains.com/fleet/#polyglot这个网站的时候发现的,于是写下了此demo.
废话不多说,直接分享代码:
- HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入css文件 -->
<link rel="stylesheet" href="./css/index.css">
<!-- 引入js文件 -->
<script src="./js/index.js"></script>
</head>
<body>
<ul class="box">
<li>
<img src="./svg/biaoqing_1.svg" alt="">
<h2>小霆</h2>
<span>A man who combines technology and beauty</span>
<div class="light"></div>
</li>
<li>
<img src="./svg/biaoqing_1.svg" alt="">
<h2>小霆</h2>
<span>A man who combines technology and beauty</span>
<div class="light"></div>
</li>
<li>
<img src="./svg/biaoqing_1.svg" alt="">
<h2>小霆</h2>
<span>A man who combines technology and beauty</span>
<div class="light"></div>
</li>
</ul>
</body>
</html>
- CSS代码
* {
/* 初始化清除盒子内外边距 */
padding: 0;
margin: 0;
}
body {
/* 弹性布局 */
display: flex;
width: 100%;
height: 100vh;
/* 水平居中 垂直居中 */
justify-content: center;
align-items: center;
background-color: #19191b;
box-sizing: border-box;
}
.box {
display: flex;
flex-direction: row;
}
.box li {
/* 弹性布局 */
display: flex;
/* 让里面的元素垂直方向排列 */
flex-direction: column;
/* 相对定位 */
position: relative;
width: 300px;
height: 300px;
background-color: #303032;
/* 清楚ul默认的小圆点 */
list-style: none;
/* 添加1像素描边 */
border: 1px solid #4c456e;
/* 圆角 */
border-radius: 10px;
/* 字体颜色 */
color: #fff;
padding: 20px;
box-sizing: border-box;
margin: 8px;
/* 溢出隐藏,light超出li就不会显示 */
overflow: hidden;
}
.box li img {
transform: translateX(-5px);
width: 80px;
}
img,
h2,
span {
margin-top: 25px;
/* 让图标文字置于最上方 */
z-index: 99;
}
.box li .light {
/* 默认隐藏,鼠标放置后再显示 */
display: none;
/* 添加绝对定位 方便等下用js绑定位置 */
position: absolute;
width: 200px;
height: 200px;
background-color: #4c16c4;
border-radius: 50%;
filter: blur(40px);
}
- JS代码
window.addEventListener('load', function() {
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
// 鼠标经过li触发事件
lis[i].addEventListener('mouseover', function() {
// 这样拿到的元素 就是当前鼠标放置的li的子元素
var light = this.querySelector('.light');
light.style.display = 'block';
// 现在开始绑定位置,鼠标移动触发事件
this.addEventListener('mousemove', function(e) {
// 获取鼠标当前位置 距离li左侧距离算法是 鼠标距离屏幕左侧的距离 - li距离屏幕左侧的距离
var x = e.pageX - this.offsetLeft - light.offsetWidth / 2;
// 距离顶部的计算方法也一样
var y = e.pageY - this.offsetTop - light.offsetHeight / 2;
// 开始绑定给light
light.style.left = x + 'px';
light.style.top = y + 'px';
// 还存在一个问题 就是鼠标不是在light的中心,只需要x-light的宽除2即可
})
})
// 鼠标离开li隐藏light
lis[i].addEventListener('mouseout', function() {
var light = this.querySelector('.light');
light.style.display = 'none';
})
}
})
666牛逼
感谢分享 赞一个
真棒/:strong /:strong/:strong/:strong