以下是一个使用纯 HTML、CSS 和 JS 实现淡粉色背景、樱花飘动和鼠标经过排斥效果的示例:

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <title>樱花动画</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="container">
        <div id="cherryBlossom"></div>
    </div>

    <script src="script.js"></script>
</body>
</html>

CSS代码(style.css):

body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #fdd2e0;
}

#container {
    position: relative;
    width: 100%;
    height: 100vh;
}

#cherryBlossom {
    position: absolute;
    top: -50px;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ffffff' width='48px' height='48px'%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3Cpath d='M7 3a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1h4.416a1.5 1.5 0 0 1 1.443 1.858l-2.667 10.667A3 3 0 0 1 16.792 19H7.208a3 3 0 0 1-2.91-2.475L1.63 5.858A1.5 1.5 0 0 1 3.073 4H7V3zm2 0h6v1H9V3zm-2 3h8l1.238 5.23A2.5 2.5 0 0 1 13.238 11H10.76a2.5 2.5 0 0 1-2.238-1.77L6 6zm8.5 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z'/%3E%3C/svg%3E');
    background-repeat: no-repeat;
    background-position: center;
    animation: fallingAnimation 10s infinite;
}

@keyframes fallingAnimation {
    0% {
        transform: translate(0, -100%);
        opacity: 0;
    }
    5%, 95% {
        opacity: 1;
    }
    100% {
        transform: translate(0, 100%);
        opacity: 0;
    }
}

JS代码(script.js):

var cherryBlossom = document.getElementById("cherryBlossom");

document.addEventListener("mousemove", function(event) {
    var x = event.clientX;
    var y = event.clientY;
    var boundingRect = cherryBlossom.getBoundingClientRect();
    var centerX = boundingRect.left + boundingRect.width / 2;
    var centerY = boundingRect.top + boundingRect.height / 2;
    var distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
    var maxDistance = Math.sqrt(Math.pow(boundingRect.width / 2, 2) + Math.pow(boundingRect.height / 2, 2));
    var scale = Math.max(1 - distance / maxDistance, 0.2);
    cherryBlossom.style.transform = "scale(" + scale + ")";
});

这个示例中,使用了一个<div>元素作为容器,设置了淡粉色背景色。樱花动画使用了一个纯SVG的背景图片,并使用CSS的background-image属性和background-repeat属性实现。动画使用CSS的@keyframes和animation属性实现樱花的缓慢下落效果。JS代码监听鼠标移动事件,并根据鼠标的位置计算鼠标与樱花中心之间的距离,然后根据距离缩放樱花的大小,实现鼠标经过时的排斥效果。

希望这个例子能帮到你!

纯HTML、CSS和JS实现淡粉色背景樱花飘动动画及鼠标排斥效果

原文地址: https://www.cveoy.top/t/topic/padx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录