<!DOCTYPE html>
<html>
<head>
    <title>简单战斗界面</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="battle-container">
        <div id="boxA" class="box">
            <span id="healthA" class="health">100</span>
        </div>
        <div id="boxB" class="box">
            <span id="healthB" class="health">100</span>
        </div>
    </div>
<pre><code>&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
</code></pre>
</body>
</html>
<pre><code>
```css
.battle-container {
    display: flex;
    justify-content: space-between;
    margin-top: 100px;
}

.box {
    width: 200px;
    height: 200px;
    background-color: #00ff00;
    border: 1px solid black;
    position: relative;
}

.health {
    position: absolute;
    top: 10px;
    left: 10px;
    font-size: 20px;
}

.box.shake {
    animation: shake 0.5s;
}

@keyframes shake {
    0% { transform: translateX(0); }
    25% { transform: translateX(-10px); }
    50% { transform: translateX(10px); }
    75% { transform: translateX(-10px); }
    100% { transform: translateX(0); }
}

.box.low-health {
    background-color: #ff0000;
}
</code></pre>
<pre><code class="language-javascript">const boxA = document.getElementById(&quot;boxA&quot;);
const boxB = document.getElementById(&quot;boxB&quot;);
const healthA = document.getElementById(&quot;healthA&quot;);
const healthB = document.getElementById(&quot;healthB&quot;);

let healthValueA = 100;
let healthValueB = 100;

function updateHealth() {
    healthA.innerText = healthValueA;
    healthB.innerText = healthValueB;

    if (healthValueA &lt;= 20) {
        boxA.classList.add(&quot;low-health&quot;);
    } else {
        boxA.classList.remove(&quot;low-health&quot;);
    }

    if (healthValueB &lt;= 20) {
        boxB.classList.add(&quot;low-health&quot;);
    } else {
        boxB.classList.remove(&quot;low-health&quot;);
    }
}

function shakeBox(box) {
    box.classList.add(&quot;shake&quot;);
    setTimeout(() =&gt; {
        box.classList.remove(&quot;shake&quot;);
    }, 500);
}

function attackBox(attacker, defender) {
    const damage = Math.floor(Math.random() * 10) + 1;
    defender.health -= damage;
    shakeBox(defender === boxA ? boxA : boxB);
    updateHealth();

    if (defender.health &lt;= 0) {
        defender.style.display = &quot;none&quot;;
        alert(`${attacker.id} wins!`);
    }
}

boxA.addEventListener(&quot;click&quot;, () =&gt; {
    attackBox(boxA, boxB);
});

boxB.addEventListener(&quot;click&quot;, () =&gt; {
    attackBox(boxB, boxA);
});
</code></pre>
<p>这个代码会创建一个战斗界面,其中有两个方块AB,初始血量为100,背景为绿色。点击A方块或B方块时,会随机扣除对方一定的血量,并在头部显示扣血数量,并且方块会抖动一下。当血量低于等于20时,方块背景会变为红色。当血量为0时,方块会消失,并弹出提示谁获胜。</p>
JS+CSS+HTML实现简单战斗界面:随机扣血、抖动效果和胜负判定

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

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