用html+css+js编写一个会动的草莓熊的代码
时间: 2023-09-22 17:07:33 浏览: 1269
以下是一个简单的草莓熊动画效果的 HTML、CSS 和 JavaScript 代码示例:
HTML:
```html
<div class="strawberry-bear-container">
<div class="strawberry-bear">
<div class="strawberry"></div>
<div class="bear">
<div class="head"></div>
<div class="body"></div>
<div class="arms"></div>
<div class="legs"></div>
</div>
</div>
</div>
```
CSS:
```css
.strawberry-bear-container {
position: relative;
width: 200px;
height: 200px;
}
.strawberry-bear {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 100px;
height: 100px;
}
.strawberry {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
border-radius: 50%;
transform: translateY(-50%) rotate(45deg);
animation: strawberry-rotate 2s linear infinite;
}
.bear {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 70%;
background-color: #f6d7b2;
border-radius: 50% 50% 0 0;
}
.head {
position: absolute;
top: -20px;
left: 50%;
transform: translateX(-50%);
width: 40px;
height: 40px;
background-color: #fff;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.body {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
width: 60px;
height: 60px;
background-color: #f6d7b2;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.arms {
position: absolute;
top: 30px;
left: 0;
width: 100%;
height: 40px;
}
.arms:before,
.arms:after {
content: "";
position: absolute;
top: 0;
width: 20px;
height: 20px;
background-color: #fff;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.arms:before {
left: 20px;
transform: rotate(45deg);
}
.arms:after {
right: 20px;
transform: rotate(-45deg);
}
.legs {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 30px;
}
.legs:before,
.legs:after {
content: "";
position: absolute;
bottom: 0;
width: 20px;
height: 20px;
background-color: #fff;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.legs:before {
left: 20px;
transform: rotate(45deg);
}
.legs:after {
right: 20px;
transform: rotate(-45deg);
}
@keyframes strawberry-rotate {
from {
transform: translateY(-50%) rotate(0);
}
to {
transform: translateY(-50%) rotate(360deg);
}
}
```
JavaScript:
```javascript
// 获取草莓熊容器元素
var bearContainer = document.querySelector(".strawberry-bear-container");
// 监听鼠标移动事件
bearContainer.addEventListener("mousemove", function (event) {
// 获取草莓熊元素
var bear = document.querySelector(".strawberry-bear");
// 计算草莓熊元素的位置和大小
var bearRect = bear.getBoundingClientRect();
// 计算鼠标在草莓熊元素内的位置
var x = event.clientX - bearRect.left;
var y = event.clientY - bearRect.top;
// 计算草莓熊元素的中心点位置
var centerX = bearRect.width / 2;
var centerY = bearRect.height / 2;
// 计算草莓熊元素的偏移量
var offsetX = (x - centerX) / centerX * 10;
var offsetY = (y - centerY) / centerY * 10;
// 应用草莓熊元素的偏移量
bear.style.transform = "translate(" + offsetX + "px, " + offsetY + "px)";
});
```
通过以上代码,你可以在浏览器中看到一个会动的草莓熊。当你鼠标在草莓熊上移动时,草莓熊会随着鼠标的移动而移动。
阅读全文