在JS中操作CSS属性命名上的区别
以前css直接写死在html中,现在可以通过js脚本去动态修改一个标签的样式。方式一:
元素.style.样式名 = “样式值”;
方式二:
元素.className = “类名”;
JS修改CSS的示例代码
需求
点按钮,修改p标签的字体、颜色、大小
代码
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>JavaScript操纵Css</title><style type="text/css">.two{color: rebeccapurple;font-size: 45px;font-family: "BIZ UDP明朝 Medium";}</style></head><script type="text/javascript">//方式一:修改多个样式属性function changeCss () {//color: blue; font‐size: 30px; font‐family: 楷体;//得到first这个pvar p1 = document.getElementById("first");//语法:元素.style.样式名=样式值;p1.style.color = "blue";p1.style.fontSize = "30px";p1.style.fontFamily = "楷体";}//方式二:首先创建一个类样式,然后一条语句一次性修改所有的样式function changeClass () {var p2 = document.getElementById("second");//语法:元素.className = "类名";p2.className = "two";}</script><body><p id="first">元素.style.样式名 = "样式值";</p><p id="second">元素.className = "类名";</p><input type="button" value="style.样式名,修改多个样式属性" onclick="changeCss()"/><input type="button" value="className,改变类样式" onclick="changeClass()"/></body></html>