有 javascript 没有 jquery 的淡入

FadeIn with javascript without jquery

我有这个代码:

document.getElementById('showRtb').addEventListener('click', function () {
    document.getElementById('rtb').style.display="inline-table";    
});

document.getElementById('hideRtb').addEventListener('click', function () {
    document.getElementById('rtb').style.display="none";    
});

但现在我想在没有 jquery 效果的情况下制作淡入动画,只需要 javascript。没有 css3 也没有 jquery。这可能吗?

您可以使用 setInterval()getComputedStyle()。另见 TheAnimationinterface

var rtb = document.getElementById("rtb"),
  timer = null;

document.getElementById("showRtb").addEventListener("click", function() {
  if (rtb.style.opacity != 1) {
    clearTimeout(timer);
    rtb.style.display = "inline-table";
    timer = setInterval(function() {
      rtb.style.opacity = +rtb.style.opacity + .10;
      if (+getComputedStyle(rtb).getPropertyValue("opacity") >= 1) {
        clearInterval(timer);
      }
    }, 100)
  }
});

document.getElementById("hideRtb").addEventListener("click", function() {
  if (rtb.style.opacity != 0) {
    clearTimeout(timer);
    timer = setInterval(function() {
      rtb.style.opacity = +rtb.style.opacity - .10;
      if (+getComputedStyle(rtb).getPropertyValue("opacity") <= 0) {
        rtb.style.display = "none";
        clearInterval(timer);
      }
    }, 100)
  }
});
#rtb {
  width: 100px;
  height: 100px;
  background: olive;
  opacity: 0;
  display: none;
}
<button id="showRtb">show</button>
<button id="hideRtb">hide</button>
<br>
<div id="rtb"></div>