这是我记录学习的地方,帮助我回忆学过的东西,方便我以后查找!
通过JS来操作CSS样式是非常又需要的,一起来学习吧。
语法:object.style.样式名= 样式的值
例如:
<!Document html>
<head>
<meat charset=" UTF-8" >
<meat name ="keywords" content=" ">
<meat name= "description" content=" ">
<title>document</title>
<style>
#box1{width:100px;
height:100px;
background-color:gary;
/*如果在样式中加入!improtant 为重点,在JS中是修改不了的。*/
}
</style>
<script>
window.onload = function(){
//获取按钮
var btn1 = document.getElementById("btn1");
//获取box1
var box1 = document.getElementById( " box1");
//为按钮绑定单机函数
btn1.onclick =function(){
//改变 box1的宽和高
//注意:样式的值是带双引号的!
box1.style.width= "300px";
box1.style.width="300px";
box1.style.backgroundColor="red";
// 如果CSS样式中带有 - 号的,在JS中是不合法的输入,要改成驼峰法(把“-“号去掉并且把减号后的字母改写成大写!!)
};
};
</script>
</head>
<body>
<div id ="box1 "></div>
<button id="btn1">点击一下</button>
</body>
</html>
同样读取css样式也是一样的操作,object.style.style name = style vaule
通过style 属性设置和读取的都是内联样式。
内联样式有较高的优先级!
在实际操作过程做一定不要忘记加 ; 分号!!!!