我希望能够将网页上的字体从默认 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;
}
最佳答案
使用类总是比使用字体系列更好:
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>
关于javascript - 想要使用 javascript 按钮来回更改字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679960/