简体   繁体   中英

Change CSS font size dynamically across application, based on user preference

I have a requirement to change the font size in application based on the user entered entry? I know about CSS variables and using it in all classes, but this has limited support across browsers.

For example, a user prefers 14px then all control and text font-size should change to 14px.

Can you please give me an idea how to achieve this?

Use font-size in REM. 1 Rem used base font-size of html. see this code

 var html = document.getElementsByTagName('html')[0]; var input = document.getElementById('font-size'); input.addEventListener('input', function(e) { html.style.fontSize = ""+e.target.value+"px"; console.log(html.style.fontSize) })
 html { font-size: 16px; } p { font-size: 2rem; }
 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati rerum numquam, dolorem ad ducimus. Commodi provident mollitia labore voluptatum itaque quasi eligendi, ipsam obcaecati nostrum cum aperiam doloremque ab consectetur?<p> <input id="font-size" type="text" value="">

If you give font-size to body as dynamically you can achieve this

 function setFont() { var x = document.getElementById("font"); if(!(x.value>0)) { alert("Enter valid input"); } else { document.getElementsByTagName("body")[0].style.fontSize=x.value +"px" ; } }
 <input id="font" placeholder="Enter Font size" type="number" /> <input type="button" value="Set" onclick="setFont()"/> <p>Example paragraph</p>

 var a = document.getElementById('text'); var inp = document.getElementById('font-size'); var btn = document.getElementById('btn') btn.addEventListener('click',function(){ x = window.getComputedStyle(a, null).getPropertyValue('font-size'); currentsize = parseFloat(x) a.style.fontSize = (inp.value) + 'px'; })
 <p id='text'>text content <p> <input id="font-size" type="text" value=""> <button id='btn'>set</button>

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.

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