如何使用JS定期更改div的宽度?

问题描述 投票:2回答:3

我在背景中有一个温度刻度(绿色到某种程度,然后是黄色,然后是红色),需要一个温度“条”,其中包括:

  1. 在固定的时间间隔之后刷新,以它定期“更新”自身的方式
  2. 根据读取的参数动态更改其宽度。现在我只想尝试使用随机数生成器(在一个范围内)

我做了这样的事,在这里创建了一个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);
}

这不行。任何人都可以帮我找到可行的解决方案吗?

javascript jquery html css
3个回答
3
投票

你应该使用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>

2
投票

我更新了你的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>

如果这是理想的结果,请告诉我。谢谢。


1
投票

你永远不会调用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>
© www.soinside.com 2019 - 2024. All rights reserved.