I am trying to change the font size of a text so that it fits the dimension of a dynamic 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.
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.'
This is the original jQuery codes I need to convert:
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
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 = ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.