【发布时间】:2017-12-12 19:34:36
【问题描述】:
我正在制作一个简单的游戏,其中的彩条会慢慢降为零。玩家必须在任何条下降到零之前单击“重新填充”按钮,否则他们会输掉。最初我尝试做一些超时和一些事情来尝试并在需要时显示警报,但是当宽度 css 样式开始过渡到 0 时,它们就会显示出来,这不是我想要的。即使延迟它也不起作用。
因此,我开始查看 blueBar css 样式的像素宽度,以尝试在该像素宽度为零时触发警报。当我手动将宽度设置为零时,我能够显示警报,但它似乎跟不上不断变化的宽度。有没有办法让变量 blueWidth 不断检查它的值,以便在它等于 0 时触发警报?
$(document).ready(function(){
// Locate the main items in the page
var blueButton = $('#blue-button');
var blueBar = $('#blue-bar');
var yellowButton = $('#yellow-button');
var yellowBar = $('#yellow-bar');
// triggers auto-decay of the blue bar
blueBar.delay(2000).queue(function(){
blueBar.css({'width': '0%', 'transition': 'width 5s linear'});
});
// refills blue bar on click, then auto-decay it after set timeout
blueButton.click(function() {
blueBar.css({'width': '100%', 'transition': 'width 0.5s linear'});
setTimeout(function(){
blueBar.css({'width': '0%', 'transition': 'width 5s linear'})
}, 2000);
});
// checks to see if blue bar zeroes out
var blueWidth = parseInt(blueBar.css('width').slice(0,-2));
console.log(blueWidth);
if(blueWidth <= 0){
alert('you lose :(');
}
// triggers auto-decay of the yellow bar
yellowBar.delay(3000).queue(function(){
yellowBar.css({'width': '0%', 'transition': 'width 2.5s linear'});
});
// refills yellow bar on click, then auto-decay it after set timeout
yellowButton.click(function() {
yellowBar.css({'width': '100%', 'transition': 'width 0.5s linear'});
setTimeout(function(){
yellowBar.css({'width': '0%', 'transition': 'width 2.5s linear'})
}, 3000);
});
});
.game {
text-align: center;
}
div {
margin: 20px 0px;
}
.empty {
width: 160px;
height: 11px;
border-radius: 11px;
margin: auto;
background: #f1f1f1;
}
.blue {
width: 100%;
height: 11px;
border-radius: 11px;
background: #bfe5ff;
}
.yellow {
width: 100%;
height: 11px;
border-radius: 11px;
background: #f8d975;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game">
<div>
<div class="empty">
<div id="blue-bar" class="blue"></div>
</div>
<button id="blue-button">refill</button>
</div>
<div>
<div class="empty">
<div id="yellow-bar" class="yellow"></div>
</div>
<button id="yellow-button">refill</button>
</div>
</div>
【问题讨论】:
标签: javascript jquery css