JavaScript通过style属性操作样式

CSS样式动态修改示例
本文介绍了一个简单的HTML页面示例,演示了如何使用JavaScript来动态地修改元素的CSS样式。当点击页面上的div元素时,该元素的大小、背景颜色及浮动属性会发生变化。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet">
<style type="text/css">
#box{
width:100px;
height:100px;
background: green;
}
</style>
</head>
<body>
<div id="box" style=''>div</div>
<script type="text/javascript">
/*
一、样式操作
通过style属性添加样式:obj.style.width
带-样式==>驼峰命名:obj.style.backgroundColor = 'red';
*/
var obj = document.getElementById('box');

 

obj.onclick = function(){
obj.style.width = 250+'px';
obj.style.height = 250+'px';
obj.style.backgroundColor = 'red';
obj.style.borderTop = '1px solid green';

}

</script>
</body>
</html>
效果如下                                          
点击前:                                        点击后:
 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title> hello world</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style type="text/css">
#box{
width:100px;
height:100px;
background: green;
margin:0 auto
}
</style>
</head>
<body>
<div id="box" style=''>div</div>


<script type="text/javascript">
/*
一、样式操作
obj.style.float = 'left';
*/
var obj = document.getElementById('box');

obj.onclick = function(){
// obj.style.cssText = 'width:250px;height:250px;border-top:1px solid green';
obj.style.float = 'left';
}
</script>
</body>
</html>
 
点击前:              

 

点击后

 

 

转载于:https://www.cnblogs.com/raulfang/p/8660450.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值