Else语句工作一次,然后停止



我试着让球长到400,当它达到400时,它会逐渐缩小到100(每次点击-50)。Else语句只工作一次,然后停止(100>150>200>250>300>350>400>350,然后停止)。

var ball2Size = 100;
var ball2SizeStep = 50;
function onBall2Click() {
var ball2 = document.querySelector(".ball2");
if (ball2Size < 400) {
ball2Size = ball2Size + 50;
} else {
ball2Size = ball2Size - 50;
}
ball2.innerText = ball2Size;
ball2.style.width = ball2Size;
ball2.style.height = ball2Size;
}
body {
background-color: black;
text-align: center;
}
h1 {
color: white;
}
div {
width: 100px;
height: 100px;
margin: auto;
margin-bottom: 10px;
border-radius: 50%;
transition: 0.3s;
line-height: 50px;
}
.ball2 {
background-color: orange;
}
<h1>The Ball</h1>
<div class="ball2" onclick="onBall2Click()">TOGGLE</div>

您可以在一个变量中存储大小是否应该减小。然后使用if语句检查size是否为400。如果是,则将该变量设置为true。如果size为100,则将该变量设置为false。

然后使用另一个if语句根据该变量增加/减少大小。

<html>
<head>
<title>Challenge</title>
<style>
body {
background-color: black;
text-align: center;
}

h1 {
color: white;
}

div {
width: 100px;
height: 100px;
margin: auto;
margin-bottom: 10px;
border-radius: 50%;
transition: 0.3s;
line-height: 50px;
}

.ball2 {
background-color: orange;
}
</style>
</head>
<body>
<h1>The Ball</h1>
<div class="ball2" onclick="onBall2Click()">TOGGLE</div>
<script>
var ball2Size = 100;
var ball2SizeStep = 50;
var shouldShrink = false;
function onBall2Click() {
var ball2 = document.querySelector(".ball2");
if (ball2Size == 400) {
shouldShrink = true;
} else if (ball2Size == 100) {
shouldShrink = false;
}
if (!shouldShrink) {
ball2Size = ball2Size + 50;
} else {
ball2Size = ball2Size - 50;
}
ball2.innerText = ball2Size;
ball2.style.width = ball2Size;
ball2.style.height = ball2Size;
}
</script>
</body>
</html>

在函数外部建立一个布尔值,以跟踪球的大小是在增长还是在缩小。另外,还要加上"px"可以动态改变小球的宽度和高度的大小。

let ball2Size = 100
const ball2SizeStep = 50
let growing = true
const ball2 = document.querySelector('.ball2')
function onBall2Click() 
{
if (ball2Size < 400 && growing) 
{
ball2Size += ball2SizeStep
growing = ball2Size < 400
} 
else 
{
ball2Size -= ball2SizeStep
growing = ball2Size <= 100
}
ball2.innerText = ball2Size
ball2.style.width = `${ball2Size}px`
ball2.style.height = `${ball2Size}px`
}
body {
background-color: black;
font-family: sans-serif;
}
h1 {
color: white;
text-align: center;
}
.ball2 {
background-color: orange;
width: 100px;
height: 100px;
margin: auto;
margin-bottom: 10px;
border-radius: 50%;
transition: 0.3s;
display: flex;
align-items: center;
justify-content: center;
}
<h1>The Ball</h1>
<div class="ball2" onclick="onBall2Click()">TOGGLE</div>

相关内容

  • 没有找到相关文章

最新更新