简体   繁体   English

如何在Javascript中修改计算的字体大小

[英]How to modify computed font-size in Javascript

I am trying to change the font size of a text so that it fits the dimension of a dynamic div. 我试图改变文本的字体大小,使其适合动态div的维度。

I have found some jquery code which fits the bill, however I can't use jquery in my code and need to convert it into vanilla javascript. 我找到了一些适合该法案的jquery代码,但是我不能在我的代码中使用jquery并且需要将其转换为vanilla javascript。

When I run the converted code I receive this error: 'Uncaught DOMException: Failed to set the 'font-size' property on 'CSSStyleDeclaration': These styles are computed, and therefore the 'font-size' property is read-only.' 当我运行转换后的代码时,我收到此错误:'未捕获DOMException:无法在'CSSStyleDeclaration'上设置'font-size'属性:计算这些样式,因此'font-size'属性是只读的。

This is the original jQuery codes I need to convert: 这是我需要转换的原始jQuery代码:

elements = $('.resize')
el = elements[_i]

and: 和:

resizeText = function () {
    var elNewFontSize
    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px'
    return $(el).css('font-size', elNewFontSize)
  }

And this is my conversion on: 这是我的转换:

elements = document.getElementsByClassName('resize')
el = elements[_i]

and: 和:

resizeText = function () {
    var elNewFontSize
    elNewFontSize = (parseInt(window.getComputedStyle(el).fontSize.slice(0, -2)) - 1) + 'px'
    window.getComputedStyle(el).fontSize = elNewFontSize
    return elNewFontSize
  }

What am I doing wrong? 我究竟做错了什么?

You need to set the new size to the element's style.fontSize property, and not the computed value that you get from window.getComputedStyle(), eg 您需要将新大小设置为元素的style.fontSize属性,而不是从window.getComputedStyle()获得的计算值,例如

el.style.fontSize = elNewFontSize;

-- -

As an aside, and not directly related, there is no reason to have the variable name twice, you can initialize it with the declaration, ie instead of: 顺便说一句,并没有直接相关,没有理由让变量名称两次,你可以用声明初始化它,即代替:

var elNewFontSize
elNewFontSize = ...

Simply write 简单写一下

var elNewFontSize = ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM