用javascript更改字体大小 [英] change font size with javascript

查看:135
本文介绍了用javascript更改字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有这个代码用3个按钮改变一个段落的字体大小,我想知道我可以使用哪个方法不重复相同的行并使这个代码更紧凑非常感谢你:)) p>

Hello i have this code to change the font size of a paragraph with 3 buttons, i would like to know wich method can i use to not repeat the same lines and make this code more compact thank you very much :)

window.addEventListener('load', inicio, false);

function inicio(){
var boton1 = document.getElementById('boton1');
var boton2 = document.getElementById('boton2');
var boton3 = document.getElementById('boton3');

boton1.addEventListener('click', fuente10, false);
boton2.addEventListener('click', fuente13, false);
boton3.addEventListener('click', fuente20, false);
} 

function fuente10(){
var parrafo = document.getElementById('parrafo');
parrafo.style.fontSize='10px'
}

function fuente13(){
var parrafo = document.getElementById('parrafo');
parrafo.style.fontSize='13px'
}

function fuente20(){
var parrafo = document.getElementById('parrafo');
parrafo.style.fontSize='20px'
}

我在想在一个for循环但我无法弄明白该怎么做:/

i was thinking in a for loop but i can't figure it out how to do it :/

推荐答案

尝试这样的事情

window.addEventListener('load', inicio, false);

function inicio(){
var boton1 = document.getElementById('boton1');
var boton2 = document.getElementById('boton2');
var boton3 = document.getElementById('boton3');

boton1.addEventListener('click', function() { setFont("10px");}, false);
boton2.addEventListener('click', function() { setFont("13px");}, false);
boton3.addEventListener('click', function() { setFont("20px");}, false);
} 

function setFont(value){
   var parrafo = document.getElementById('parrafo');
   parrafo.style.fontSize= value;
}

更新
另一个approch(未经测试,但应该有效)

Update A different approch (not tested, but should work)

    window.addEventListener('load', inicio, false);
function inicio() {
    var fontDetails = {"boton1" : "10px" , "boton2" : "13px" , "boton3" : "20px"};
    var parrafo = document.getElementById('parrafo');
    var domElement  = "";
    var element  = "";

    for (element in fontDetails)
    {
        domElement = document.getElementById(element);
        domElement.addEventListener('click', function() { parrafo.style.fontSize= fontDetails[element]; }, false);
    }
}

您还可以删除窗口加载事件处理程序和函数inicio并尝试自我执行这样的函数

You can also remove the window load event handler and function inicio and try self executing function like this

(function() { //your code here } )();

这篇关于用javascript更改字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆