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

Want to change fonts back and forth using javascript button

本文关键字:javascript 按钮 改变 字体      更新时间:2023-09-26

我希望能够改变一个网页上的字体,从其默认的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;
}

使用class总是比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>

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

让你快速上手: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>

当然,你可以在css类中添加Font-family和其他任何东西