问题描述
我一直在使用香草JavaScript创建音频播放器,以操纵HTML <audio>
元素.
I have been creating an audio player using vanilla JavaScript to manipulate the HTML <audio>
element.
播放器具有动态尺寸,所有元素都按比例缩放以适合父级DIV.
The player is of dynamic size, with all elements scaled to fit the parent DIV.
我已经应用了所有可以找到的方法来缩放字体以适合父容器并以一种似乎可行的方式组合了解决方案,但是我无法使字体超赞的图标以相同的方式缩放.
I have applied all methods I can find for scaling font to fit the parent container and combined solutions in a way that seems functional, however I cannot make font-awesome icons scale in the same way.
图标的包含方式如下:
<div>
<button>
<a>
<i class="fa fa-play">
</i>
</a>
</button>
</div>
我的解决方案通过实现window.addEventListener('resize', resizeFont);
来工作,其中resizeFont
函数的定义如下:
My solution works by implementing window.addEventListener('resize', resizeFont);
, with the resizeFont
function defined as follows:
function resizeFont() {
var elements = document.getElementsByClassName('resize');
console.log(elements);
if (elements.length < 0) {
return;
}
_len = elements.length;
for (_i = 0; _i < _len; _i++) {
var el = elements[_i];
el.style.fontSize = "100%";
for (var size = 100; el.scrollHeight > el.clientHeight; size -= 10) {
el.style.fontSize = size + '%';
}
}
}
我在CSS中设置了div
,button
或a
元素的字体大小,以便为font-awesome的默认font-size: inherit
样式提供一些输入.
I set font-size of the div
,button
or a
element in CSS in order to provide some input for font-awesome's default font-size: inherit
style.
resizeFont();
函数在页面加载时被调用一次,以确保显示的字体被缩放以适合音频播放器的初始大小.
The resizeFont();
function is called once on page load, ensuring that the fonts displayed are scaled to fit the audio player's initial size.
我尝试将.resize
类应用于各种元素,结果如下:
I have attempted to apply the .resize
class to various elements with the following results:
div
:字体不会显示,或者字体显示为默认大小,然后在调整窗口大小时消失.
div
: font won't display, or font displays at default size and then disappears on window resize.
a
:与div
相同的结果.
i
:resizeFont()
在窗口加载时确实将图标缩放到适合容器的正确大小,但是在触发窗口调整大小事件时字体仍然消失.
i
: resizeFont()
on window load does scale the icon to the correct size to fit the container, but the font still disappears when the window resize event is fired.
因此,我想应该将.resize
类应用于i
元素,但是我需要以某种方式定义其大小或容器的大小.
So, I guess that the .resize
class is supposed to be applied to the i
element, but that I somehow need to define its size, or its container's size, differently.
推荐答案
将类.jcfResize
添加到任何包含应调整大小的字体的元素中.
Add the class .jcfResize
to any elements containing font which should be resized.
将以下javascript代码添加到页面/站点:
Add the following javascript code to the page/site:
function jcfResizeText() {
var elements = document.getElementsByClassName('jcfResize');
if (elements.length < 0) {
return;
}
_len = elements.length;
for (_i = 0; _i < _len; _i++) {
var el = elements[_i];
el.style.fontSize = "100%";
for (var size = 100; el.scrollHeight > el.clientHeight; size -= 10) {
el.style.fontSize = size + '%';
}
}
}
jcfResizeText();
window.addEventListener('resize', jcfResizeText);
这篇关于Vanilla JavaScript:调整字体大小,以适合容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!