用html写一个动态的爱心
时间: 2024-06-08 11:10:55 浏览: 12
您好,让我来尝试回答您的问题。
首先,感谢您的提问。以下是一个示例,演示如何使用HTML,CSS和JavaScript创建动态的爱心。
HTML代码:
```html
<div class="heart-container">
<div id="heart"></div>
</div>
```
CSS代码:
```css
.heart-container {
width: 50px;
height: 50px;
position: relative;
}
#heart {
width: 50px;
height: 50px;
background: url(https://i.imgur.com/67OY8wO.png);
background-size: cover;
position: absolute;
top: 0;
left: 0;
animation: beat 1s ease-in-out infinite;
}
@keyframes beat {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
```
JavaScript代码:
```javascript
// 计算爱心的位置
var heartContainer = document.querySelector('.heart-container');
function setPosition() {
heartContainer.style.top = Math.random() * window.innerHeight + 'px';
heartContainer.style.left = Math.random() * window.innerWidth + 'px';
}
setPosition();
window.addEventListener('resize', setPosition);
// 创建爱心
function createHeart() {
var heart = document.createElement('div');
heart.classList.add('heart-container');
heart.innerHTML = '<div id="heart"></div>';
document.body.appendChild(heart);
setTimeout(function() {
heart.remove();
}, 5000);
}
setInterval(createHeart, 300);
```
这段代码创建了一个具有CSS样式和JavaScript动画效果的爱心。每次调用`createHeart`函数都会在随机位置创建一个新的爱心。爱心会在5秒钟后从屏幕消失。同时,`setPosition`函数在窗口大小发生变化时计算新的位置。
希望这能够帮到您。如果您还有其他问题,请随时提出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)