使用 Javascript 中的 setTimeout 函数更改 H1 的文本颜色

我的 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();

}


泛舟湖上清波郎朗
浏览 128回答 4
4回答

杨__羊羊

感谢所有这些答案,但我自己找到了最简单、最干净的解决方案。只是前一个函数中的 settimeout 函数,以循环方式。它更加漂亮和清晰。下面是代码片段。<body>&nbsp; &nbsp; <h1 id="first">Text 1</h1>&nbsp; &nbsp; <h1 id="second">Text 2</h1>&nbsp; &nbsp; <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>

肥皂起泡泡

您必须使用循环数组和超时来睡眠并调用该函数listElements包含所有要突出显示的元素及其突出显示时间startAutoIndex每次调用该函数时都会递增,因此它将首先从元素 id 开始var startAutoIndex = 0function startAuto() {&nbsp; &nbsp; let listElements = [&nbsp; &nbsp; &nbsp; &nbsp; {id: "first", timer: 10000},&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {id: "second", timer: 13000},&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {id: "third", timer: 26000}&nbsp; &nbsp; ]&nbsp; &nbsp; function colorHeader(currentIndex) {&nbsp; &nbsp; &nbsp; &nbsp; for (let index = 0; index < listElements.length; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const element = listElements[index]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (currentIndex != index)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById(element.id).style.color = '#333'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById(element.id).style.color = '#32A067'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; let currentIndex =&nbsp; &nbsp; &nbsp; &nbsp; ((startAutoIndex % listElements.length) + listElements.length) %&nbsp; &nbsp; &nbsp; &nbsp; listElements.length&nbsp; &nbsp; colorHeader(currentIndex)&nbsp; &nbsp; setTimeout(startAuto, listElements[currentIndex].timer)&nbsp; &nbsp; startAutoIndex = currentIndex + 1}

喵喵时光机

您可以将主计时器包含在一个间隔内,并将每个突出显示事件作为单独的超时。我还会向您要查询的元素添加一个类,或者只选择所有h1元素。您还可以提供固定超时,它会为您计算元素之间的超时。window.startAuto = () => {&nbsp; start({&nbsp; &nbsp; selector : '.highlighter',&nbsp; &nbsp; timeouts : [ 1000, 2000, 1000 ], // or, for a fixed timout: 1000&nbsp; &nbsp; callback : (el, index, activeIndex) => {&nbsp; &nbsp; &nbsp; el.classList.toggle('active', index === activeIndex);&nbsp; &nbsp; }&nbsp; });};const defaultOptions = {&nbsp; selector : '',&nbsp; timeouts : [],&nbsp; initialDelay : 0};const start = (options) => {&nbsp; let opts = Object.assign({}, defaultOptions, options);&nbsp; opts.elements = Array.from(document.querySelectorAll(opts.selector));&nbsp; let interval = 0;&nbsp; if (!Array.isArray(opts.timeouts)) {&nbsp; &nbsp; opts.timeouts = fillArray(opts.timeouts, opts.elements.length);&nbsp; }&nbsp; interval = opts.timeouts.reduce((t, x) => t + x, 0);&nbsp; opts.timeouts = normalizeTimeouts(opts.timeouts);&nbsp; setTimeout(() => {&nbsp; &nbsp; update(opts);&nbsp; &nbsp; setInterval(update, interval, opts);&nbsp; }, opts.initialDelay);};const normalizeTimeouts = (timeouts) => {&nbsp; return timeouts.reduce((results, timeout, index, all) => {&nbsp; &nbsp; return results.concat(timeout + all.slice(0, index).reduce((t, x) => t + x, 0));&nbsp; }, [0]);};const update = (opts) => {&nbsp; opts.timeouts.slice(0, opts.timeouts.length -1).forEach((timeout, index) => {&nbsp; &nbsp; setTimeout(() => {&nbsp; &nbsp; &nbsp; opts.elements.forEach((element, i) => {&nbsp; &nbsp; &nbsp; &nbsp; return opts.callback.call(element, element, i, index);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }, timeout);&nbsp; })};const fillArray = (value, count) => new Array(count).fill(value);.active {&nbsp; color: green;}<body onload="startAuto()">&nbsp; <h1 class="highlighter" id="first">Text 1</h1>&nbsp; <h1 class="highlighter" id="second">Text 2</h1>&nbsp; <h1 class="highlighter" id="third">Text 3</h1></body>这里有超动态;可重用的类。document.addEventListener('DOMContentLoaded', () => main());const main = () => {&nbsp; let looper = new Looper({&nbsp; &nbsp; selector : '.highlighter',&nbsp; &nbsp; timeouts : [ 1000, 2000, 1000 ], // or, for a fixed timout: 1000&nbsp; &nbsp; callback : (el, index, activeIndex) => {&nbsp; &nbsp; &nbsp; el.classList.toggle('active', index === activeIndex);&nbsp; &nbsp; },&nbsp; &nbsp; initialDelay : 1000,&nbsp; &nbsp; autoStart : true&nbsp; })&nbsp;&nbsp;&nbsp; document.querySelector('#stop-btn').addEventListener('click', (e) => {&nbsp; &nbsp; looper.stop();&nbsp; });&nbsp;&nbsp;&nbsp; document.querySelector('#restart-btn').addEventListener('click', (e) => {&nbsp; &nbsp; looper.stop();&nbsp; &nbsp; looper.start();&nbsp; });}class Looper {&nbsp; constructor(options) {&nbsp; &nbsp; let opts = Object.assign({}, Looper.defaultOptions, options);&nbsp; &nbsp; this.elements = Array.from(document.querySelectorAll(opts.selector));&nbsp; &nbsp; if (!Array.isArray(opts.timeouts)) {&nbsp; &nbsp; &nbsp; opts.timeouts = this.__fillArray(opts.timeouts, this.elements.length);&nbsp; &nbsp; }&nbsp; &nbsp; this.interval = opts.timeouts.reduce((t, x) => t + x, 0);&nbsp; &nbsp; this.timeouts = this.__normalizeTimeouts(opts.timeouts);&nbsp; &nbsp; this.initialDelay = opts.initialDelay;&nbsp; &nbsp; this.autoStart = opts.autoStart;&nbsp; &nbsp; this.callback = opts.callback;&nbsp; &nbsp; this.__startupId = null;&nbsp; &nbsp; this.__processId = null;&nbsp; &nbsp; this.__subprocessIds = this.__fillArray(null, this.elements.length);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (this.autoStart === true) this.start();&nbsp; }&nbsp;&nbsp;&nbsp; start() {&nbsp; &nbsp; if (this.callback == null) {&nbsp; &nbsp; &nbsp; throw new Error('callback function is undefined');&nbsp; &nbsp; }&nbsp; &nbsp; if (this.__processId == null) {&nbsp; &nbsp; &nbsp; this.__startupId = setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp; this.__update();&nbsp; &nbsp; &nbsp; &nbsp; this.__processId = setInterval(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.__update();&nbsp; &nbsp; &nbsp; &nbsp; }, this.interval);&nbsp; &nbsp; &nbsp; }, this.initialDelay);&nbsp; &nbsp; }&nbsp; }&nbsp; stop() {&nbsp; &nbsp; this.__subprocessIds.forEach((id, index) => {&nbsp; &nbsp; &nbsp; if (id != null) {&nbsp; &nbsp; &nbsp; &nbsp; clearTimeout(id);&nbsp; &nbsp; &nbsp; &nbsp; this.__subprocessIds[index] = null;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; if (this.__processId != null) {&nbsp; &nbsp; &nbsp; clearInterval(this.__processId);&nbsp; &nbsp; &nbsp; this.__processId = null;&nbsp; &nbsp; }&nbsp; &nbsp; if (this.__startupId != null) {&nbsp; &nbsp; &nbsp; clearTimeout(this.__startupId);&nbsp; &nbsp; &nbsp; this.__startupId = null;&nbsp; &nbsp; }&nbsp; }&nbsp; __update() {&nbsp; &nbsp; let self = this;&nbsp; &nbsp; self.timeouts.slice(0, this.timeouts.length -1).forEach((timeout, index) => {&nbsp; &nbsp; &nbsp; self.__subprocessIds[index] = setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp; self.elements.forEach((element, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.callback.call(element, element, i, index);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; }, timeout);&nbsp; &nbsp; })&nbsp; }&nbsp; __normalizeTimeouts(timeouts) {&nbsp; &nbsp; return timeouts.reduce((results, timeout, index, all) => {&nbsp; &nbsp; &nbsp; return results.concat(timeout + all.slice(0, index).reduce((t, x) => t + x, 0));&nbsp; &nbsp; }, [0]);&nbsp; }&nbsp; __fillArray(value, count) {&nbsp; &nbsp; return new Array(count).fill(value);&nbsp; }}Looper.defaultOptions = {&nbsp; selector : '',&nbsp; timeouts : [],&nbsp; initialDelay : 0,&nbsp; autoStart : false}.active {&nbsp; color: green;}<div>&nbsp; <h2 class="highlighter" id="first">Text 1</h2>&nbsp; <h2 class="highlighter" id="second">Text 2</h2>&nbsp; <h2 class="highlighter" id="third">Text 3</h2></div><button id="stop-btn">Stop</button><button id="restart-btn">Restart</button>

紫衣仙女

您可以将 setTimeout 与 Promise 一起使用来实现您想要的结果。看看我的片段:var first = document.getElementById('first');&nbsp; &nbsp; var second = document.getElementById('second');&nbsp; &nbsp; var third = document.getElementById('third');&nbsp; const promiseTimeout = (delay, element, newColor) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; return new Promise((resolve, reject) => {&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; element.style.color = newColor;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve() // when this fires, .then gets called&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }, delay)&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; function start(){&nbsp; &nbsp; first.style.color = "green";&nbsp; &nbsp; promiseTimeout(10000, first, "#333")&nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; return second.style.color = "green";&nbsp; &nbsp; })&nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; return promiseTimeout(15000, second, "#333")&nbsp; &nbsp; })&nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; third.style.color = "green";&nbsp; &nbsp; &nbsp; return promiseTimeout(18000, third, "#333")&nbsp; &nbsp; })&nbsp; &nbsp; .then(() => start());&nbsp; }&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5