如何在点击javascript

时间:2017-01-20 05:14:05

标签: javascript setinterval

我希望能够在点击时切换setInterval。

这是我开始间隔的代码:

var clock = document.querySelector('#hexTime');
var hexClock = document.querySelector('#hexClock');
function run() {
  var time = new Date();
  var hours = (time.getHours() % 12).toString();
  var minutes = time.getMinutes().toString();
  var seconds = time.getSeconds().toString();
  if(hours.length < 2) {
    hours = '0' + hours;
  }
  if(minutes.length < 2) {
    minutes = '0' + minutes;
  }
  if(seconds.length < 2) {
    seconds = '0' + seconds;
  }
  var clockStr = hours + ' : ' + minutes + ' : ' + seconds;
  var hexStr = '#' + hours + minutes + seconds;

  clock.textContent = clockStr;
  hexClock.textContent = hexStr;
  document.body.style.backgroundColor = hexStr;
}

run();

setInterval(run, 1000);

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:0)

首先,添加一个会监听点击的元素(最好是一个按钮),给它一个ID:

var clock = document.querySelector('#hexTime');
var hexClock = document.querySelector('#hexClock');
function run() {
  var time = new Date();
  var hours = (time.getHours() % 12).toString();
  var minutes = time.getMinutes().toString();
  var seconds = time.getSeconds().toString();
  if(hours.length < 2) {
    hours = '0' + hours;
  }
  if(minutes.length < 2) {
    minutes = '0' + minutes;
  }
  if(seconds.length < 2) {
    seconds = '0' + seconds;
  }
  var clockStr = hours + ' : ' + minutes + ' : ' + seconds;
  var hexStr = '#' + hours + minutes + seconds;

  clock.textContent = clockStr;
  hexClock.textContent = hexStr;
  document.body.style.backgroundColor = hexStr;
}


var myButton = document.querySelector('#myToggleButton');

// this will hold the information about the interval
var myInterval = null;

// the event listener for the click event
myButton.addEventListener("click", function(){
  if(myInterval){ // if we have an interval (myInterval != null)
    clearInterval(myInterval); // clear it
    myInterval = null; // make it null again
  }
  else{ // if we don't have an interval (myIntervall == null)
    myInterval = setInterval(run, 1000); // start one
  }
});

// if you don't want the interval to start by default then remove the next line
myInterval = setInterval(run, 1000);

然后为该元素添加一个事件监听器,并在单击时设置或清除间隔,如:

<alerta [messageStatus]="teste"></alerta>

secound in child view check the input with ngIf

<div *ngIf="messageStatus" class="alert alert-warning alert-dismissable">

    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>{{ messageStatus }}
  </div>