想要使用javascript按钮来回更改字体

时间:2015-09-20 13:32:45

标签: javascript html button fonts

我希望能够将网页上的字体从默认的CSS样式“Amatic SC”更改为Times New Roman,以便于阅读。我有一个按钮,它成功地将其更改为Times New Roman,但无法将其更改回来。我的javascript如下

function changeFont(){
var fon = document.getElementById("posts");
    if (fon.style.fontFamily == "Amatic SC") {
        fon.style.font = "150% Times New Roman";
    }
    else {
        fon.style.font = "200% Amatic SC";
    }
}

HTML看起来像这样:

<div id="posts">Content</div>
<button type="button" onclick="changeFont()">Change the font!</button>

CSS:

#posts {
  background-color: #F0F0F1;
  margin: 64px 64px 64px 64px;
  padding: 10px;
  font-family: 'Amatic SC', cursive;
  font-size: 200%;
  border: 5px solid red;
  overflow: auto;
  box-shadow: 0 0 10px #777777;
}

3 个答案:

答案 0 :(得分:0)

也许你实际上没有那种字体。尝试切换到'Arial'或'Helvetica'或'草书'。

答案 1 :(得分:0)

让你快速小提琴:http://jsfiddle.net/mikepmtl/hbL4L4py/

function changeFont(){

    var post = document.getElementById("posts");

    if (post.className == "post_normal") {
        post.className = "post_big";
    } else {
        post.className = "post_normal";
    }

}



.post_normal{
    font-size: 100%;
}

.post_big {
    font-size: 200%; 
}


<div id="posts" class="post_normal">
   This is my posts
</div>
<button id="my_button" onclick="changeFont();">Press Me</button>

当然,您可以将Font-family和其他任何内容添加到css类中。

答案 2 :(得分:0)

使用类比使用font-family更好:

function changeFont() {
  var fon = document.getElementById("posts");
  if (fon.className == "amatic") {
    fon.className = 'roman';
  } else {
    fon.className = 'amatic';
  }
}
#posts {
  background-color: #F0F0F1;
  margin: 64px 64px 64px 64px;
  padding: 10px;
  border: 5px solid red;
  overflow: auto;
  box-shadow: 0 0 10px #777777;
}
.amatic {
  font-family: 'Amatic SC', cursive;
  font-size: 200%;
}
.roman {
  font-family: 'Times New Roman', cursive;
  font-size: 200%;
}
<div id="posts" class="amatic">Content</div>
<button type="button" onclick="changeFont()">Change the font!</button>