您的位置:首页 > Web前端 > CSS

js操作样式总结

2012-09-10 21:41 204 查看
一、有关元素的样式操作

1.className属性

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css" rel="stylesheet">
.test {
background: red;
font-size: 30px;
font-weight: bolder;
}
</style>
</head>
<body>
<button onclick="addClass()">添加类</button>

<div id="pos" >你好</div>
</body>
<script type="text/javascript">
var pos = document.getElementById('pos');
function addClass() {
pos.className = "test";//设置pos的类为test
}
</script>
</html>


2.style属性

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<button onclick="changeStyle()">改变style</button>

<div id="pos" style="font-size: 30px; font-weight: bolder;" >你好</div>
</body>
<script type="text/javascript">
var pos = document.getElementById('pos');
function changeStyle() {         /*此种方式不会重写style,但如果有同名的属性,会覆盖掉之前的值。
                比如设置style.fontSize="40px;,会覆盖掉之前的font-size:30px"*/
pos.style.width = "200";
pos.style.height = "300";//注意,一定要加上"px"。
pos.style.border = "4px solid black";
pos.style.backgroundColor = "red";//从第二个单词开始后,首字母大写
}
</script>
</html>


3.style的cssText属性

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css" rel="stylesheet">
.test {
background: red;
}
</style>
</head>
<body>
<button onclick="changeCssText()">改变cssText</button>
<button onclick="showCssText()">显示cssText</button>

<div id="pos" style="font-size: 30px; font-weight: bolder;" class="test">你好</div>
</body>
<script type="text/javascript">
var pos = document.getElementById('pos');
function showCssText() {
alert(pos.style.cssText);  /*这里只会显示style属性中的值, 而不会显示test类中的值。*/
}
function changeCssText() {
pos.style.cssText = "width:250px; height:30px;";  /*给cssText属性赋值会重写style属性的值,原来设置的字体大小和加粗都没有了。*/
}
</script>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: