JavaScript 中调整文字大小通常是通过操作 CSS 样式来实现的。以下是一些基础概念和相关方法:
style
属性。<head>
部分使用 <style>
标签定义样式。<link>
标签引入外部 CSS 文件。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change Font Size</title>
</head>
<body>
<p id="myParagraph">这是一个段落。</p>
<button onclick="increaseFontSize()">增大字体</button>
<button onclick="decreaseFontSize()">减小字体</button>
<script>
function increaseFontSize() {
var element = document.getElementById("myParagraph");
var style = window.getComputedStyle(element, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
element.style.fontSize = (fontSize + 1) + "px";
}
function decreaseFontSize() {
var element = document.getElementById("myParagraph");
var style = window.getComputedStyle(element, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
// Don't allow the font size to go below 12px
element.style.fontSize = Math.max(fontSize - 1, 12) + "px";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change Font Size</title>
<style>
.small-font {
font-size: 12px;
}
.medium-font {
font-size: 16px;
}
.large-font {
font-size: 20px;
}
</style>
</head>
<body>
<p id="myParagraph" class="medium-font">这是一个段落。</p>
<button onclick="changeFontSize('small')">小字体</button>
<button onclick="changeFontSize('medium')">中字体</button>
<button onclick="changeFontSize('large')">大字体</button>
<script>
function changeFontSize(size) {
var element = document.getElementById("myParagraph");
element.className = size + "-font";
}
</script>
</body>
</html>
问题:字体大小调整不生效。
window.onload
或 DOMContentLoaded
事件)。通过上述方法,你可以有效地在 JavaScript 中控制文字的大小,以适应不同的需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云