实操实现:笑脸表情眼睛随着鼠标的移动而变化,如下效果。
时间: 2024-05-09 12:22:04 浏览: 22
这种效果可以通过JavaScript和CSS来实现。首先,在HTML代码中,需要添加一个div元素,其中包含一个笑脸图像,并且设置一个类名,比如“smile”。其次,在CSS中,需要使用transform属性和translateX()、translateY()函数来改变图像的位置,以便让眼睛跟随鼠标的移动而变化。最后,在JavaScript代码中,需要获取鼠标的位置,并且使用mousemove事件来绑定一个函数,该函数会计算出眼睛的位置,并且改变CSS样式以更新眼睛的位置。具体的代码实现过程可以参考下面的示例代码:
HTML代码:
```html
<div class="smile">
<img src="smile.png" alt="smile" />
</div>
```
CSS代码:
```css
.smile {
position: relative;
display: inline-block;
}
.smile img {
width: 100px;
height: 100px;
}
.smile .left-eye {
position: absolute;
width: 20px;
height: 20px;
background-color: black;
border-radius: 50%;
transform: translateX(-50%) translateY(-50%);
top: 45%;
left: 35%;
}
.smile .right-eye {
position: absolute;
width: 20px;
height: 20px;
background-color: black;
border-radius: 50%;
transform: translateX(-50%) translateY(-50%);
top: 45%;
left: 65%;
}
```
JavaScript代码:
```javascript
const smile = document.querySelector('.smile');
const leftEye = smile.querySelector('.left-eye');
const rightEye = smile.querySelector('.right-eye');
smile.addEventListener('mousemove', (event) => {
const x = event.clientX / window.innerWidth;
const y = event.clientY / window.innerHeight;
const leftEyeX = (x * 40) + 35;
const leftEyeY = (y * 20) + 45;
const rightEyeX = (x * 40) + 65;
const rightEyeY = (y * 20) + 45;
leftEye.style.left = `${leftEyeX}%`;
leftEye.style.top = `${leftEyeY}%`;
rightEye.style.left = `${rightEyeX}%`;
rightEye.style.top = `${rightEyeY}%`;
});
```