【问题标题】:jQuery UI datepicker update styles while clock running时钟运行时 jQuery UI datepicker 更新样式
【发布时间】:2021-03-27 21:21:44
【问题描述】:

我正在使用 jquery ui datepicker(计时器创建)以及自定义的 datetimepicker。

我正在尝试更新按钮的 onclick 样式。更新后一直重置为默认样式。

预期:

我得到了什么:

jsFiddle

HTML

<div class="container">
  <p>Date: <input type="text" id="datetimepicker"></p>
  <div id="clock"></div>
</div>    

<div class="btnHolder">
  <input type="button" value="Change font color" id="fontColor" />
  <input type="button" value="Change font size" id="fontSize" />
</div>

脚本

$(document).ready(function(){

  $(function() {
    $( "#datetimepicker" ).datetimepicker({ 
      minDate:0,
      timeInput: true,
      timeFormat: "hh:mm tt"
    });
  });

  // on changing date initilize the countdown again
  $("#datetimepicker").change(function(){
    init($(this).val());
  })

  function init(dt){
    $('#clock').countdown(dt).on('update.countdown', function(event) {
      var $this = $(this).html(event.strftime(''
      + '<span>%-w</span> week%!w '
      +'<span>%-d</span> day%!d '
      + '<span>%H</span> hr '
      + '<span>%M</span> min '
      + '<span>%S</span> sec'));
    });
  }

  //initilize counter on load with some default date
  //init("2016/11/25");

});

jQuery(document).on('click', '#fontColor', function(){
  jQuery('#clock span').css({'color': 'red'})
})

jQuery(document).on('click', '#fontSize', function(){
  jQuery('#clock span').css({'font-size': '20px'})
})

【问题讨论】:

    标签: jquery jquery-ui jquery-ui-datepicker


    【解决方案1】:

    您每秒都在用未设置样式的星期、日期等替换内容。&lt;span&gt;...&lt;/span&gt;s。因此,即使您在单击按钮时在跨度上正确设置了样式,它也会每秒再次被无样式的内容替换一次。 您可以在外部#clock 元素上设置一个类

    jQuery(document).on('click', '#fontColor', function() {
      jQuery('#clock').addClass('red');
    });
    

    并添加以下css:

    .red > span {
      color: red;
    }
    

    &gt; 选择#clock.red 元素的直接子元素并将其颜色设置为红色。 (更多关于子组合器here。)

    更新了 JSFiddle here.

    【讨论】:

    • @Sebastian Richner,感谢您的回答。但是添加类并不能解决我的问题,因为用户可以从调色板中选择颜色,从下拉列表中选择字体系列等...
    • @Reddy,在这种情况下,您还可以根据所选值更新$('#clock').countdown(dt).on('update.countdown', function(event) { ... } 中的颜色、字体等。您也可以只更新每个跨度的内容,而不是完全替换它们,因此您不必每秒都应用样式/类。
    • @Sebastian Richner,您能否提供小提琴,因为我无法做到这一点请?
    • @Reddy,当然,这是一个非常基本的更新版本:jsfiddle.net/jcpru32t/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多