簡體   English   中英

想要使用javascript按鈕來回更改字體

[英]Want to change fonts back and forth using javascript button

我希望能夠將網頁上的字體從其默認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;
}

也許您實際上沒有該字體。 嘗試切換到“ Arial”或“ Helvetica”或“ cursive”。

讓您快速擺弄: 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類中。

與類一起玩總是比字體家族更好:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM