无法增加-减小字体大小

时间:2018-11-21 12:38:27

标签: javascript html

我想连续增加和减小字体大小。只是没有发生。它增加了,但随后停止并开始闪烁,就像某些东西阻止了它减少一样。 告诉我这里怎么了。

 var change = document.querySelector("p");
    change.style.fontSize = "20px";
    var t = 20;
    setInterval(function(){
        t++;
        change.style.fontSize = t+"px";
        if(t==50){
            setInterval(function(){
                t--;
                change.style.fontSize = t+"px";
                if(t==20){
                    clearInterval();
                }
            },50);
        }  
    },50);
<p>example text</p>

2 个答案:

答案 0 :(得分:1)

function toggleFontSize(selector, init, increase = true) {
  selector.style.fontSize = `${init}px`;

  const handle = setInterval(function() {
    init = increase ? init + 1 : init - 1;
    selector.style.fontSize = `${init}px`;
    if (init == 50 && increase) {
      clearInterval(handle);
      toggleFontSize(selector, init, false);
    } else if (init == 20 && !increase) {
      clearInterval(handle);
      toggleFontSize(selector, init, true);
    }
  }, 50);
}

toggleFontSize(document.querySelector("p"), 20);
<p>Hello world.</p>

但是,最好使用绝对平滑的CSS动画。

p {
  font-size: 20px;
  animation: toggleFontSize 1.5s linear infinite alternate;
}

@keyframes toggleFontSize {
  from {
    font-size: 20px;
  }
  to {
    font-size: 50px;
  }
}
<p>Hello world.</p>

答案 1 :(得分:0)

您可以更好地将增加和减少部分分开:

请参阅附件JSFiddle

https://jsfiddle.net/5tzafspo/5/

var change = document.querySelector("p");
change.style.fontSize = "20px";
var currentSize = 20;
var minSize = 20;
var maxSize = 50;
var intervalTime = 50;

increaseSize();

function increaseSize(){

  var interval = setInterval(function(){
    currentSize++;

    change.style.fontSize = currentSize+"px";

    if(currentSize === maxSize){
      clearInterval(interval);
      decreaseSize();
    }
  }, intervalTime);
}

function decreaseSize(){

  var interval = setInterval(function(){
    currentSize--;

    change.style.fontSize = currentSize+"px";

    if(currentSize === minSize){
      clearInterval(interval);
      increaseSize();
    }
  }, intervalTime);
}