简体   繁体   English

CSS或jQuery:如何为使用getElementById获得的元素添加淡入淡出效果?

[英]CSS or jQuery: How to add a fade effect to an element got with getElementById?

I think this is a pretty simple question. 我认为这是一个非常简单的问题。

I have a script which replace a text on my website. 我有一个脚本替换了我网站上的文本。 I would love to add a fade-effect while replacing. 我希望在替换时添加淡入淡出效果。 What should I do? 我该怎么办?

 var target = document.getElementById('target'); var titles = [ 'Text1', 'Text2', 'Text3' ]; function newTitle () { var i = (Math.random() * titles.length) | 0; target.innerText = titles[i]; } newTitle(); 
  <p id="target"></p> <button onclick="newTitle()">Replace</div> 

Here is an example. 这是一个例子。 I utilized setInterval and change the text's opacity over time - just vanilla JavaScript 我使用了setInterval并随着时间的推移更改了文本的opacity -只是普通的JavaScript

 var target = document.getElementById('target'); var titles = [ 'Text1', 'Text2', 'Text3' ]; function newTitle() { document.getElementById("trigger").disabled = true; var i = (Math.random() * titles.length) | 0; var width = 0; var opacity = 0; target.style.opacity = opacity; target.innerText = titles[i]; var c = setInterval(fade, 100); function fade() { if (opacity>1) { clearInterval(c); document.getElementById("trigger").disabled = false; return; } else { opacity += 0.1; target.style.opacity = opacity; } } } 
 <p id="target">Text1</p> <button id="trigger" onclick="newTitle()">Replace</div> 

  1. Add a CSS effect to transition , specific for opacity . transition添加CSS效果,特定于opacity

  2. In your function, change the element opacity to 0. 在函数中,将元素不透明度更改为0。

  3. Add a timeout before changing the text (use the same time you added in the transition effect). 在更改文本之前添加一个超时(使用在过渡效果中添加的相同时间)。

  4. When timer ends, change the text and opacity back to 1. 计时器结束时,将文本和不透明度更改回1。

See below code: 请参阅以下代码:

 var target = document.getElementById('target'); var titles = [ 'Text1', 'Text2', 'Text3' ]; function newTitle () { var i = (Math.random() * titles.length) | 0; target.style.opacity = "0"; setTimeout(function(){ target.innerText = titles[i]; target.style.opacity = "1"; }, 600); } newTitle(); 
 #target{ transition: opacity .6s ease; } 
 <p id="target"></p> <button onclick="newTitle()">Replace</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM