通过纯javascript动态调整字体大小
我有一个类似的代码:通过纯javascript动态调整字体大小,javascript,Javascript,我有一个类似的代码: var a = document.createElement('div'); a.style.width = '200px'; a.style.fontSize = fontSize(a.offsetWidth, 5); a.innerHTML = 'Example'; document.body.appendChild(a); function fontSize(reference, factor){ return (reference*factor)/100 +
var a = document.createElement('div');
a.style.width = '200px';
a.style.fontSize = fontSize(a.offsetWidth, 5);
a.innerHTML = 'Example';
document.body.appendChild(a);
function fontSize(reference, factor){
return (reference*factor)/100 + 'px';
}
但是,当我运行它时,元素字体大小似乎是0px。console.log
返回预期值tho
类似的代码适用于我尝试过的javascript对象:
var Object = function(target){
var default = {
fontSize: fontSize(target.clientWidth, 5);
}
}
我做错了什么?您的逻辑很好,但在尝试检索其大小之前,您应该将元素附加到DOM:
var a = document.createElement('div');
a.style.width = '200px';
a.innerHTML = 'Example';
document.body.appendChild(a);
a.style.fontSize = fontSize(a.offsetWidth, 5);
function fontSize(reference, factor) {
return (reference * factor) / 100 + 'px';
}
HtmleElement.offsetWidth只读属性返回元素的布局宽度。通常,元素的offsetWidth是一种度量,它包括元素边框、元素水平填充、元素垂直滚动条(如果存在,如果渲染)和元素CSS宽度
当您尝试读取offsetWidth
时,新创建的div
元素没有附加到文档中,因此它的布局宽度为0
,因此您的字体大小为0px
在测量div在文档中占用的空间之前,需要将其放入文档中
或者,您需要使用除
offsetWidth
以外的值(例如style.width
只需将a.style.fontSize=fontSize(a.offsetWidth,5);
放在document.body.appendChild(a);
之后
var a=document.createElement('div');
a、 style.width='200px';
a、 innerHTML='Example';
文件.正文.附件(a);
a、 style.fontSize=fontSize(a.offsetWidth,5);//在计算文档的offsetWidth之前,需要先在文档中附加“a”
参考-
你有任何浏览器限制吗?@SirmPotato我不知道。它适用于第二个代码示例,但不适用于同一代码表中的第一个代码示例。你为什么不为此使用css类?@Shilly我是一个初学者,正在练习构建模块,并尝试使用尽可能少的依赖项。你在问你的浏览器对于没有内容且没有父节点的div的offsetWidth
。如果没有0
,您希望该节点的宽度是多少?并且(0*5)/100+'px'=='0px'
除以100不会使其变小。您可以将其乘以1000,最后仍然是零。
var a = document.createElement('div');
a.style.width = '200px';
a.innerHTML = 'Example';
document.body.appendChild(a);
a.style.fontSize = fontSize(a.offsetWidth, 5); // <--- Move here
function fontSize(reference, factor){
return (reference*factor)/100 + 'px';
}
var a = document.createElement('div');
a.style.width = '200px';
document.body.appendChild(a);
a.style.fontSize = fontSize(a.offsetWidth, 5);
a.innerHTML = 'Example';
function fontSize(reference, factor){
return (reference*factor)/100 + 'px';
}