更改按钮的颜色根据时间

时间:2017-07-05 11:10:19

标签: jquery html css

我想根据换班时间改变按钮的颜色。同样,如果它是早班,则按钮颜色应该是蓝色,而在晚上它应该自动变为红色或任何不同的颜色。我需要四种不同的颜色。任何人都可以帮助我吗?



$(document).ready(function(){
  $("#hex").on('change', function(){  
    var hex = $("#hex").val();
    $("#btn").css({"background-color":hex});
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="hex" />
<input type="button" id="btn" />
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

以下是帮助您的示例代码。只需从Date()获取小时数,使用if-else条件或switch-case并添加您想要的颜色:

$(document).ready(function() {
  var hours = new Date().getHours();
  var color = '#d00';
  if (hours < 12)
    color = '#FFF';
  else if (hours > 12 && hours < 15)
    color = '#000';
  $("#btn").css({
    "background-color": color
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="hex" />
<input type="button" id="btn" />

答案 1 :(得分:0)

我刚刚在6小时内分四组打破24小时。根据您的需要进行更改。使用脚本:

$(document).ready(function() {
 var hours = new Date().getHours();
 var color = '';
 if (hours <= 6)
   color = '#f00';
 else if (hours > 6 && hours <= 12)
   color = '#0f0';
 else if (hours > 12 && hours <= 18)
   color = '#00f';
 else if (hours > 18 && hours <= 24)
   color = '#ff0';
 $("#btn").css({"background-color": color});
});
相关问题