亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Javascript 中的 setTimeout 函數更改 H1 的文本顏色

使用 Javascript 中的 setTimeout 函數更改 H1 的文本顏色

泛舟湖上清波郎朗 2023-12-04 14:38:58
我的 html 中有三個標題。在頁面加載時,我想逐個更改這些標題的顏色,并且應該從最后一個標題之后的第一個標題重新開始。我嘗試過 JS 的 setTimeout 函數,但無法得到我想要的結果。它應該像這樣工作:“文本 1” – 綠色 10 秒“文本 2” – 綠色 15 秒“文本 3” – 綠色 18 秒在“文本 3”之后,應再次以“文本 1”開始下面是我的代碼。<body onload="startAuto()">    <h1 id="first">Text 1</h1>    <h1 id="second">Text 2</h1>    <h1 id="third">Text 3</h1></body>我第一次使用了以下 JavaScript,但當它到達文本 3 時,它不會返回到文本 1。function startAuto() {  function first() {    document.getElementById('first').style.color = "#32A067";  }  function second() {    setTimeout(function() {      document.getElementById('first').style.color = "#333";      document.getElementById('second').style.color = "#32A067";    }, 13000);  }  second();  function third() {    setTimeout(function() {      document.getElementById('first').style.color = "#333";      document.getElementById('second').style.color = "#333";      document.getElementById('third').style.color = "#32A067";    }, 26000);  }  third();}
查看完整描述

4 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

感謝所有這些答案,但我自己找到了最簡單、最干凈的解決方案。只是前一個函數中的 settimeout 函數,以循環方式。它更加漂亮和清晰。下面是代碼片段。


<body>

    <h1 id="first">Text 1</h1>

    <h1 id="second">Text 2</h1>

    <h1 id="third">Text 3</h1>

</body>



<script>

first();


function first()

{


document.getElementById('third').style.color="#333";


document.getElementById('first').style.color="#32A067";


setTimeout(second,10000);


}



function second()

{


document.getElementById('first').style.color="#333";

document.getElementById('second').style.color="#32A067";


setTimeout(third,15000);


}




function third()

{


document.getElementById('second').style.color="#333";

document.getElementById('first').style.color="#32A067";


setTimeout(first,18000);



}

</script>



查看完整回答
反對 回復 2023-12-04
?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

您必須使用循環數組和超時來睡眠并調用該函數


listElements包含所有要突出顯示的元素及其突出顯示時間


startAutoIndex每次調用該函數時都會遞增,因此它將首先從元素 id 開始


var startAutoIndex = 0


function startAuto() {


    let listElements = [

        {id: "first", timer: 10000}, 

        {id: "second", timer: 13000}, 

        {id: "third", timer: 26000}

    ]


    function colorHeader(currentIndex) {

        for (let index = 0; index < listElements.length; index++) {

            const element = listElements[index]

            if (currentIndex != index)

                document.getElementById(element.id).style.color = '#333'

            else {

                document.getElementById(element.id).style.color = '#32A067'

            }

        }

    }


    let currentIndex =

        ((startAutoIndex % listElements.length) + listElements.length) %

        listElements.length


    colorHeader(currentIndex)


    setTimeout(startAuto, listElements[currentIndex].timer)


    startAutoIndex = currentIndex + 1


}


查看完整回答
反對 回復 2023-12-04
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

您可以將主計時器包含在一個間隔內,并將每個突出顯示事件作為單獨的超時。


我還會向您要查詢的元素添加一個類,或者只選擇所有h1元素。


您還可以提供固定超時,它會為您計算元素之間的超時。


window.startAuto = () => {

  start({

    selector : '.highlighter',

    timeouts : [ 1000, 2000, 1000 ], // or, for a fixed timout: 1000

    callback : (el, index, activeIndex) => {

      el.classList.toggle('active', index === activeIndex);

    }

  });

};


const defaultOptions = {

  selector : '',

  timeouts : [],

  initialDelay : 0

};


const start = (options) => {

  let opts = Object.assign({}, defaultOptions, options);

  opts.elements = Array.from(document.querySelectorAll(opts.selector));

  let interval = 0;

  if (!Array.isArray(opts.timeouts)) {

    opts.timeouts = fillArray(opts.timeouts, opts.elements.length);

  }

  interval = opts.timeouts.reduce((t, x) => t + x, 0);

  opts.timeouts = normalizeTimeouts(opts.timeouts);

  setTimeout(() => {

    update(opts);

    setInterval(update, interval, opts);

  }, opts.initialDelay);

};


const normalizeTimeouts = (timeouts) => {

  return timeouts.reduce((results, timeout, index, all) => {

    return results.concat(timeout + all.slice(0, index).reduce((t, x) => t + x, 0));

  }, [0]);

};


const update = (opts) => {

  opts.timeouts.slice(0, opts.timeouts.length -1).forEach((timeout, index) => {

    setTimeout(() => {

      opts.elements.forEach((element, i) => {

        return opts.callback.call(element, element, i, index);

      });

    }, timeout);

  })

};


const fillArray = (value, count) => new Array(count).fill(value);

.active {

  color: green;

}

<body onload="startAuto()">

  <h1 class="highlighter" id="first">Text 1</h1>

  <h1 class="highlighter" id="second">Text 2</h1>

  <h1 class="highlighter" id="third">Text 3</h1>

</body>

這里有超動態;可重用的類。


document.addEventListener('DOMContentLoaded', () => main());


const main = () => {

  let looper = new Looper({

    selector : '.highlighter',

    timeouts : [ 1000, 2000, 1000 ], // or, for a fixed timout: 1000

    callback : (el, index, activeIndex) => {

      el.classList.toggle('active', index === activeIndex);

    },

    initialDelay : 1000,

    autoStart : true

  })

  

  document.querySelector('#stop-btn').addEventListener('click', (e) => {

    looper.stop();

  });

  

  document.querySelector('#restart-btn').addEventListener('click', (e) => {

    looper.stop();

    looper.start();

  });

}


class Looper {

  constructor(options) {

    let opts = Object.assign({}, Looper.defaultOptions, options);

    this.elements = Array.from(document.querySelectorAll(opts.selector));

    if (!Array.isArray(opts.timeouts)) {

      opts.timeouts = this.__fillArray(opts.timeouts, this.elements.length);

    }

    this.interval = opts.timeouts.reduce((t, x) => t + x, 0);

    this.timeouts = this.__normalizeTimeouts(opts.timeouts);

    this.initialDelay = opts.initialDelay;

    this.autoStart = opts.autoStart;

    this.callback = opts.callback;

    this.__startupId = null;

    this.__processId = null;

    this.__subprocessIds = this.__fillArray(null, this.elements.length);

    

    if (this.autoStart === true) this.start();

  }

  

  start() {

    if (this.callback == null) {

      throw new Error('callback function is undefined');

    }

    if (this.__processId == null) {

      this.__startupId = setTimeout(() => {

        this.__update();

        this.__processId = setInterval(() => {

          this.__update();

        }, this.interval);

      }, this.initialDelay);

    }

  }


  stop() {

    this.__subprocessIds.forEach((id, index) => {

      if (id != null) {

        clearTimeout(id);

        this.__subprocessIds[index] = null;

      }

    });

    if (this.__processId != null) {

      clearInterval(this.__processId);

      this.__processId = null;

    }

    if (this.__startupId != null) {

      clearTimeout(this.__startupId);

      this.__startupId = null;

    }

  }


  __update() {

    let self = this;

    self.timeouts.slice(0, this.timeouts.length -1).forEach((timeout, index) => {

      self.__subprocessIds[index] = setTimeout(() => {

        self.elements.forEach((element, i) => {

          return self.callback.call(element, element, i, index);

        });

      }, timeout);

    })

  }


  __normalizeTimeouts(timeouts) {

    return timeouts.reduce((results, timeout, index, all) => {

      return results.concat(timeout + all.slice(0, index).reduce((t, x) => t + x, 0));

    }, [0]);

  }


  __fillArray(value, count) {

    return new Array(count).fill(value);

  }

}


Looper.defaultOptions = {

  selector : '',

  timeouts : [],

  initialDelay : 0,

  autoStart : false

}

.active {

  color: green;

}

<div>

  <h2 class="highlighter" id="first">Text 1</h2>

  <h2 class="highlighter" id="second">Text 2</h2>

  <h2 class="highlighter" id="third">Text 3</h2>

</div>


<button id="stop-btn">Stop</button>

<button id="restart-btn">Restart</button>


查看完整回答
反對 回復 2023-12-04
?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

您可以將 setTimeout 與 Promise 一起使用來實現您想要的結果。看看我的片段:


var first = document.getElementById('first');

    var second = document.getElementById('second');

    var third = document.getElementById('third');




  const promiseTimeout = (delay, element, newColor) =>

    {

      return new Promise((resolve, reject) => {

        setTimeout(() => {

          

          element.style.color = newColor;

          resolve() // when this fires, .then gets called

          

        }, delay)

      });

    }


  function start(){


    first.style.color = "green";


    promiseTimeout(10000, first, "#333")

    .then(() => {

      return second.style.color = "green";

    })

    .then(() => {

      return promiseTimeout(15000, second, "#333")

    })

    .then(() => {

      third.style.color = "green";

      return promiseTimeout(18000, third, "#333")

    })

    .then(() => start());

  }


  start();

<h1 id="first">Text 1</h1>


<h1 id="second">Text 2</h1>


<h1 id="third">Text 3</h1>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


查看完整回答
反對 回復 2023-12-04
  • 4 回答
  • 0 關注
  • 199 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號