正文
改变 HTML 样式 Object.style.property=new style;
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
改变 HTML 样式
HTML DOM 允许 JavaScript 改变 HTML 元素的样式。如何改变 HTML 元素的样式呢?
语法:
Object.style.property=new style;
注意:
Object是获取的元素对象,如通过document.getElementById("id")获取的元素。
基本属性表(property):
注意:
该表只是一小部分CSS样式属性,其它样式也可以通过该方法设置和修改。
看看下面的代码:
改变 <p> 元素的样式,将颜色改为红色,字号改为20,背景颜色改为蓝:
<p id="pcon">Hello World!</p>
<script>
var mychar = document.getElementById("pcon");
mychar.style.color="red";
mychar.style.fontSize="20";
mychar.style.backgroundColor ="blue";
</script>
结果:
任务
现在我们来改变下HTML中元素的CSS样式:
1. 在右边编辑器中,第12行补充代码,修改h2标签的样式,将颜色设为红色。
2. 在右边编辑器中,第13行补充代码,修改h2标签的样式,将背景颜色设为灰色(#CCC)。
3. 在右边编辑器中,第14行补充代码,修改h2标签的样式,将宽设为300px。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>style样式</title>
</head>
<body>
<h2 id="con">I love JavaScript</h2>
<p> JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<script type="text/javascript">
var mychar= document.getElementById("con");
mychar.style.color="yellow";
mychar.style.backgroundColor:"#CCC";
mychar.style.width=300px;
</script>
</body>
</html>
HTML DOM 允许 JavaScript 改变 HTML 元素的样式。如何改变 HTML 元素的样式呢?
语法:
Object.style.property=new style;
注意: Object是获取的元素对象,如通过document.getElementById("id")获取的元素。
基本属性表(property):
注意: 该表只是一小部分CSS样式属性,其它样式也可以通过该方法设置和修改。
看看下面的代码:
改变 <p> 元素的样式,将颜色改为红色,字号改为20,背景颜色改为蓝:
<p id="pcon">Hello World!</p>
<script>
var mychar = document.getElementById("pcon");
mychar.style.color="red";
mychar.style.fontSize="20";
mychar.style.backgroundColor ="blue";
</script>
结果:
任务
现在我们来改变下HTML中元素的CSS样式:
1. 在右边编辑器中,第12行补充代码,修改h2标签的样式,将颜色设为红色。
2. 在右边编辑器中,第13行补充代码,修改h2标签的样式,将背景颜色设为灰色(#CCC)。
3. 在右边编辑器中,第14行补充代码,修改h2标签的样式,将宽设为300px。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>style样式</title>
</head>
<body>
<h2 id="con">I love JavaScript</h2>
<p> JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<script type="text/javascript">
var mychar= document.getElementById("con");
mychar.style.color="yellow";
mychar.style.backgroundColor:"#CCC";
mychar.style.width=300px;
</script>
</body>
</html>