V2版本: 改进操作界面,统一表单样式,更多工具支持批量生成,欢迎使用 到达~


文库 阅读
作者: xiaoyu 11/01 21:02:37

JS怎样操作HTML元素的style属性?

操作 CSS 样式最简单的方法,就是使用网页元素节点的getAttribute()方法、setAttribute()方法和removeAttribute()方法,或直接读写或删除网页元素的style属性。

1、设置style样式

<div id='root'></div>
let divObj = document.getElementById('root');

divObj.setAttribute(
  'style',
  'background-color:gray; border:1px solid yellow;'
);

上面的代码相当于下面的HTML代码。

<div style="background-color:gray; border:1px solid yellow;" /></div>

style本身还是一个对象,可以直接获取属性值或者写入值。


divObj.style.backgroundColor='green';
divObj.style.height='100px'

2、获取style

console.log(divObj.style.backgroundColor);
console.log(divObj.getAttribute('style'));

3、删除style

删除一个元素的所有行内样式,最简便的方法设置成空字符串

styleObj.cssText = '';

4、更多示例

单个更新

<div id='example'></div>
var styleObj = document.querySelector('#example').style;

styleObj.backgroundColor = 'green';
styleObj.width = '100px';
styleObj.height = '100px';
styleObj.fontSize = '1.5em';

多个更新cssText

styleObj.cssText = 'background-color: green;'
  + 'border: 1px solid yellow;'
  + 'height: 100px;'
  + 'width: 100px;';

About

操作 CSS 样式最简单的方法,就是使用网页元素节点的getAttribute()方法、setAttribute()方法和removeAttribute()方法,或直接读写或删除网页元素的style属性。

Resources

发布

未发布任何资源
首页 喜欢 我的 定制
定制咨询
微信二维码
扫一扫上面的二维码,加我为朋友。
微信扫码周一至周六服务
接定制开发需求