我在背景中有一个温度刻度(绿色到某种程度,然后是黄色,然后是红色),需要一个温度“条”,其中包括:
我做了这样的事,在这里创建了一个div
<div id="temperatureBar" style="background-color: black; height: 20px;"></div>
并使用了一些jQuery
function refreshTemperature(){
var width = (Math.random() * (100 - 1)) + 1;
setInterval(function () {
$('#temperatureBar').fadeOut('slow');
$(document).getElementById('temperatureBar').style.width = width+"px";
$('#temperatureBar').fadeIn('slow');
refreshTemperature();
}, 5000);
}
这不行。任何人都可以帮我找到可行的解决方案吗?
你应该使用jquery的$.css
方法。
你可能没有注意到的另一件事是你的代码中每5秒调用一次setInterval
,每次调用都会启动另一个setInterval
。
这意味着在几分钟后,您将有大量的事件等待被调用,这将导致各种各样的问题。请改用setTimeout
。
这是一个工作样本:
function refreshTemperature() {
setTimeout(function() {
var elem = $('#temperatureBar')
var width = (Math.random() * (100 - 1)) + 1;
elem.fadeOut('slow');
elem.css('width', width + "px");
elem.fadeIn('slow');
refreshTemperature();
}, 5000);
}
refreshTemperature()
#temperatureBar {
background-color: tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="temperatureBar">
My size changes
</div>
我更新了你的js代码。现在宽度会定期变化。
function refreshTemperature(){
var width = (Math.random() * (100 - 1)) + 1;
$('#temperatureBar').fadeOut('slow');
$('#temperatureBar').css('width', width + "px");
$('#temperatureBar').fadeIn('slow');
}
setInterval(function () {
refreshTemperature();
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="temperatureBar" style="background-color: black; height: 20px;"></div>
如果这是理想的结果,请告诉我。谢谢。
你永远不会调用refreshTemperature()
,顺便说一句,为什么不使用CSS代替jQuery。
.temp {
min-height: 40px;
box-shadow: 0px 2px 3px 0px grey;
min-width: 10px;
display: inline-block;
-webkit-animation: color-swap 5s ease infinite;
-ms-animation: color-swap 5s ease infinite;
-o-animation: color-swap 5s ease infinite;
animation: color-swap 5s ease infinite;
}
@keyframes color-swap {
0% {
background-color: ghostwhite;
min-width: 30px;
}
10% {
background-color: yellow;
min-width: 50px;
}
30% {
background-color: orange;
min-width: 80px;
}
60% {
background-color: red;
min-width: 150px;
}
}
<div class="temp"></div>