jquery fadein / fadeout文本仅使用一次点击按钮自动显示

时间:2015-02-12 08:13:54

标签: javascript

HTML:

<span class="js-btn btn">Click me</span>
<div class='js-fade is-hidden'>You look amazing!</div>

的CSS:

.is-hidden {
  display: none;
}

.btn {
  background: #ccc;
  border-radius: 3px;
  display: inline-block;
  padding: 5px;
}

body {
  padding: 40px;
}

JS:

// fade out

function fadeOut(el){
  el.style.opacity = 1;

  (function fade() {
    if ((el.style.opacity -= .1) < 0) {
      el.style.display = 'none';
      el.classList.add('is-hidden');
    } else {
      requestAnimationFrame(fade);
    }
  })();
}

// fade in

function fadeIn(el, display){
  if (el.classList.contains('is-hidden')){
    el.classList.remove('is-hidden');
  }
  el.style.opacity = 0;
  el.style.display = display || "block";

  (function fade() {
    var val = parseFloat(el.style.opacity);
    if (!((val += .1) > 1)) {
      el.style.opacity = val;
      requestAnimationFrame(fade);
    }
  })();
}

var btn = document.querySelector('.js-btn');
var el = document.querySelector('.js-fade');

btn.addEventListener('click', function(e){
  if(el.classList.contains('is-hidden')){
    fadeIn(el);
  }
  else {
    fadeOut(el);
  }
});

当我点击按钮时,我需要它显示“你看起来很神奇”。它会在5秒后隐藏起来。这是我的jsfiddle:https://jsfiddle.net/5cvsm1a2/

我可以知道怎么做吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用setTimeout()之类的

var timer;
btn.addEventListener('click', function (e) {
    clearTimeout(timer);
    if (el.classList.contains('is-hidden')) {
        fadeIn(el);
        timer = setTimeout(function () {
            fadeOut(el);
        },5000)
    } else {
        fadeOut(el);
    }
});

// fade out

function fadeOut(el) {
  el.style.opacity = 1;

  (function fade() {
    if ((el.style.opacity -= .1) < 0) {
      el.style.display = 'none';
      el.classList.add('is-hidden');
    } else {
      requestAnimationFrame(fade);
    }
  })();
}

// fade in

function fadeIn(el, display) {
  if (el.classList.contains('is-hidden')) {
    el.classList.remove('is-hidden');
  }
  el.style.opacity = 0;
  el.style.display = display || "block";

  (function fade() {
    var val = parseFloat(el.style.opacity);
    if (!((val += .1) > 1)) {
      el.style.opacity = val;
      requestAnimationFrame(fade);
    }
  })();
}

var btn = document.querySelector('.js-btn');
var el = document.querySelector('.js-fade');
var timer;
btn.addEventListener('click', function(e) {
  clearTimeout(timer);
  if (el.classList.contains('is-hidden')) {
    fadeIn(el);
    timer = setTimeout(function() {
      fadeOut(el);
    }, 5000)
  } else {
    fadeOut(el);
  }
});
.is-hidden {
  display: none;
}
.btn {
  background: #ccc;
  border-radius: 3px;
  display: inline-block;
  padding: 5px;
}
body {
  padding: 40px;
}
<span class="js-btn btn">Click me</span>
<div class='js-fade is-hidden'>You look amazing!</div>

答案 1 :(得分:0)

我看到你的代码只包含js,但是当你在询问jquery解决方案时(这更简单),你有一些:

$('.js-btn').on('click', function() {
  $('.js-fade').fadeIn().delay(5000).fadeOut();
});