[英]Element that automatically toggles with javascript
I'm trying to make an element that toggles by itself.我正在尝试制作一个可以自行切换的元素。 For a example, I want
<p>Text1</p>
to switch to <p>Text2</p>
in 1 second.例如,我希望
<p>Text1</p>
<p>Text2</p>
。 Is there any javascript code I can use?我可以使用任何 javascript 代码吗?
Here's an example of what i'm trying to do:这是我正在尝试做的一个例子:
You could use the setTimeout(//function,n*1000) function in order for it to be done automatically after n seconds您可以使用 setTimeout(//function,n*1000) function 以便在 n 秒后自动完成
With your example lets say you have:用你的例子可以说你有:
let s = 1000; // second in milliseconds let n = 3; //let's say you want it to change after 3 seconds function changeText() { document.getElementById('text').innerText = 'Text2' } setTimeout(() => { changeText() }, n * s); // you could also use setTimeout(function () { changeText() }, n * s);
<p id="text">Text1</p> <!-- give the element an id ("text") in this example -->
You need to assign a class or an ID to element, eg.您需要为元素分配 class 或 ID,例如。
<p id="el">...</p>
, so that you can query it later on. <p id="el">...</p>
,以便您以后可以查询它。 Then, get it viadocument.getElementById
or document.getElementByClassName
: document.getElementById('el')
.然后,通过
document.getElementById
或document.getElementByClassName
获取它: document.getElementById('el')
。
Now you got the element, time to change the text inside it, so access it via the innerText property, then assign a new value.现在你得到了元素,是时候改变它里面的文本了,所以通过 innerText 属性访问它,然后分配一个新值。
Alright, you want it to do it in one second, so set a timeout:好吧,你希望它在一秒钟内完成,所以设置一个超时:
setTimeout(() => { /** ... */ }, 1000);
Note: 1000 is 1 second.注意:1000 是 1 秒。
An easy way would be to assign each element an id.一种简单的方法是为每个元素分配一个 id。 Then in javascript, call
setInterval
or setTimeout
.然后在 javascript 中,调用
setInterval
或setTimeout
。 Every second, get the documents by id and toggle their CSS visibility style.每秒钟,通过 id 获取文档并切换其 CSS 可见性样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.