如何使div中的文本内容重复增加和减少字体大小?

时间:2016-02-24 16:42:00

标签: javascript jquery html css animation

我想知道是否可以让div的文本内容每秒重复增加和减少字体大小。这将产生一种效果,其中文本似乎在向后移动之前移近观察者,理想情况下它将是平滑过渡并且看起来不像2帧gif。

这是我尝试使用Javascript每秒更改字体大小:

<div id="textdiv">ZOOM</div>
<script>
function zoomtext(){
   var textdiv = document.getElementById("textdiv");
   textdiv.style.fontSize = "20px";
   textdiv.style.fontSize = "25px";

   setTimeout(zoomtext, 1000);
}
</script>

这不起作用,我不确定此代码是否会导致平滑过渡。 也许可以通过将字体改变十分之一像素来进行平滑过渡(例如:20px,20.1px,20.2px ......依此类推,直到25px,然后以相同的方式将其减少到20px)。

我担心这种方法可能导致Javascript函数不断运行,这可能会减慢我的页面速度。

有没有更好的方法来达到这个效果?

5 个答案:

答案 0 :(得分:4)

使用带有比例变换的CSS过渡。字体大小过渡从不平滑,transform上的过渡很便宜。

.grow { 
    transition: all .2s ease-in-out;
}
.grow:hover {
    transform: scale(1.5);
}

重复可以通过CSS3动画实现:

.grow {
  width: 100px;
  text-align: center;
  animation: grow-animation 2s linear infinite;
}

@keyframes grow-animation {
  0% { transform: scale(1); }
  50% {transform: scale(2); }
  100% {transform: scale(1); }
}

答案 1 :(得分:3)

使用CSS Animations可以达到相同的效果。它非常简单,也比使用Javascript好得多。

您需要为您的元素分配animation属性,然后定义该属性。

#textdiv {
   animation: textgrowth 1s infinite alternate;
}

@keyframes textgrowth {
    0% {
    font-size: 20px;
    }
    100% {
    font-size: 25px;
    }
}

请务必在CSS规则的末尾添加alternate,以便动画来回播放。

答案 2 :(得分:1)

您可以使用CSS animations而不是javascript。

一些HTML示例:

<!DOCTYPE html>
    <head>
        <title>keyframes text size animation test</title>
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>
        <p id="textdiv">ZOOM</p>
    </body>
</html>

和CSS

body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
}
#textdiv {
    -webkit-animation: adjustText 1s infinite alternate;
    -moz-animation:    adjustText 1s infinite alternate;
    -o-animation:      adjustText 1s infinite alternate;
    animation:         adjustText 1s infinite alternate;
}

@keyframes adjustText {
  from {
    font-size: 20px;
  }

  to {
    font-size: 25px;
  }
}

以下是此示例的working codepen

答案 3 :(得分:1)

如果它只是在屏幕上缩放,而不是也不增长容器,那么scale();应该是你想要的:

&#13;
&#13;
#textdiv {
  -webkit-animation: zoom1-2 infinite 1s;
          animation: zoom1-2 infinite 1s;
  -webkit-transform-origin:0 0 ;
          transform-origin:0 0 ;
  font-size:20px;
}
@-webkit-keyframes zoom1-2 {
  50% {
    -webkit-transform: scale(1.2);
            transform: scale(1.2);
  }
}
@keyframes zoom1-2 {
  50% {
    -webkit-transform: scale(1.2);
            transform: scale(1.2);
  }
}
&#13;
<div id="textdiv">ZOOM</div>
<div>don't push me</div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

试试这个:

function zoomtext(){
   var textdiv = document.getElementById("textdiv");
   var fontSize = textdiv.style.fontSize;
  
   if (fontSize !== '48px') {
     textdiv.style.fontSize = '48px';
   }
   else {
     textdiv.style.fontSize = '21px';
   }

  setTimeout(zoomtext, 1000);
}


zoomtext();
<div id="textdiv">ZOOM</div>