如何让div中的文字内容反复增减字体大小? [英] How to make the text content in a div increase and decrease in font size repeatedly?

查看:27
本文介绍了如何让div中的文字内容反复增减字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<div id="textdiv">ZOOM</div><脚本>函数缩放文本(){var textdiv = document.getElementById("textdiv");textdiv.style.fontSize = "20px";textdiv.style.fontSize = "25px";设置超时(缩放文本,1000);}

这不起作用,我不确定此代码是否会导致平滑过渡.也许可以通过将字体更改十分之一像素来实现平滑过渡(例如:20px、20.1px、20.2px 等等,直到 25px,然后以相同的方式将其减小回 20px).

我担心该方法可能会导致 Javascript 函数不断运行,这可能会降低我的页面速度.

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

解决方案

你可以使用 达到同样的效果CSS 动画.这也很简单,而且比使用 Javascript 要好得多.

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

#textdiv {动画:textgrowth 1s 无限交替;}@keyframes 文本增长 {0% {字体大小:20px;}100% {字体大小:25px;}}

请务必在 CSS 规则的末尾添加 alternate 以使动画来回切换.

I’m wondering if it’s possible to have the text content of a div increase and decrease in font size repeatedly every second. This would give an effect where the text seems to move closer to the viewer before moving back, ideally it would be a smooth transition and wouldn’t look like a 2 frame gif.

This is my attempt using Javascript to change the font size every second:

<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>

This isn’t working, and I’m not sure that this code would result in a smooth transition. Perhaps it’s possible to make a smooth transition by changing the font by tenths of a pixel (for example: 20px, 20.1px, 20.2px …and so on until 25px, and then decreasing it back to 20px in the same way).

I’m worried that method might result in a Javascript function running constantly, which might slow down my page.

Is there a better way to get this effect?

解决方案

You can achieve the same effect using CSS Animations. It's pretty easy, too, and far better than using Javascript for that.

You need to assign your element the animation property, which you then define.

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

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

Be sure to add alternate at the end of your CSS rule to make the animation go back and forth.

这篇关于如何让div中的文字内容反复增减字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆