<!DOCTYPE html>
<html>
<head>
  <title>战斗界面 - 动态扣血动画效果</title>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <div class="battle-container">
    <div class="box" id="boxA"></div>
    <div class="box" id="boxB"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>
<p>/* styles.css */
.battle-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}</p>
<p>.box {
width: 200px;
height: 50px;
margin: 10px;
background-color: green;
position: relative;
}</p>
<p>.box::before {
content: &quot;&quot;;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
transform-origin: left center;
}</p>
<p>/* script.js */
// 模拟血量参数
var healthA = 100;
var healthB = 100;</p>
<p>// 更新方框血量
function updateHealth() {
var boxA = document.getElementById('boxA');
var boxB = document.getElementById('boxB');</p>
<p>boxA.style.width = healthA + 'px';
boxB.style.width = healthB + 'px';
}</p>
<p>// 扣血动画
function deductHealth() {
var decrement = 10; // 扣减血量
var duration = 500; // 动画持续时间</p>
<p>// 扣减A方框血量
healthA -= decrement;
if (healthA &lt; 0) healthA = 0;</p>
<p>// 扣减B方框血量
healthB -= decrement;
if (healthB &lt; 0) healthB = 0;</p>
<p>// 更新血量显示
updateHealth();</p>
<p>// 根据血量计算红色背景的宽度百分比
var percentageA = (100 - healthA) + &quot;% &quot;;
var percentageB = (100 - healthB) + &quot;% &quot;;</p>
<p>// 设置动画效果
document.getElementById('boxA').style.animation = 'deduct ' + duration + 'ms';
document.getElementById('boxA').style.animationFillMode = 'forwards';
document.getElementById('boxA').style.animationDelay = '0s';
document.getElementById('boxA').style.animationTimingFunction = 'linear';
document.getElementById('boxA').style.animationIterationCount = '1';</p>
<p>document.getElementById('boxB').style.animation = 'deduct ' + duration + 'ms';
document.getElementById('boxB').style.animationFillMode = 'forwards';
document.getElementById('boxB').style.animationDelay = '0s';
document.getElementById('boxB').style.animationTimingFunction = 'linear';
document.getElementById('boxB').style.animationIterationCount = '1';</p>
<p>document.styleSheets[0].insertRule(<code>@keyframes deduct { 0% {width: 100%;} 100% {width: ${percentageA};} }</code>, document.styleSheets[0].cssRules.length);</p>
<p>document.styleSheets[0].insertRule(<code>@keyframes deduct { 0% {width: 100%;} 100% {width: ${percentageB};} }</code>, document.styleSheets[0].cssRules.length);
}</p>
<p>// 调用扣血动画
deductHealth();</p>

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

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