<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态添加类名</title>
<style>
#icon {font-size: 15px;}
.red {/*预先设置好类*/
width: 300px;
background-color: red;
padding: 10px;
color: yellow;
border: 5px solid #ccc;
}
.yellow {/*预先设置好类*/
width: 300px;
padding: 10px;
border: 10px solid #ccc;
background-color: yellow;
color: red;
}
</style>
<script>
window.onload = function(){
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
var con = document.getElementById('con');
var num = 15;//默认字号大小,在此基础上进行增减
btn1.onclick = function(){
num ++; //字号增加1
// alert(num);查看弹出的num
con.style.fontSize = num + 'px';//拼接成像素单位
}
btn2.onclick = function(){
num --;
con.style.fontSize = num + 'px';
}
btn3.onclick = function(){
// 添加类名
con.className = 'red';
}
btn4.onclick = function(){
con.className = 'yellow';
}
}
</script>
</head>
<body>
<input type="button" value="+" id="btn1">
<input type="button" value="-" id="btn2">
<input type="button" value="红色" id="btn3">
<input type="button" value="黄色" id="btn4">
<p id="con">我是段落我是段落。。。</p>
</body>
</html>
注意:
手动设置属性如下:
// con.style.color = 'red';
// con.style.width = '300px';
// con.style.background = 'red';
// con.style.padding = '20px';
// con.style.color = 'yellow';
// con.style.border = '5px solid #ccc';