js修改样式属性(【前端学习笔记—使用JS修改样式】)
导读:JS修改样式的九种方式 1.直接设置style的属性...
JS修改样式的九种方式
1.直接设置style的属性
style属性可以设置或返回元素的内联样式,对于更改同一个元素的同一种样式 ,设置style属性的优先级较高
语法:element.style.property = value property为CSS属性名 ,如:color ,margin 。如果属性名原来包含“- ” ,则需转换为小驼峰形式 ,如:backgroundColor ,marginLeft 。 var box = document.querySelector(div) box.style.color = "#fff" // 将元素中文字设置为白色 box.style.marginLeft = "100px" // 将元素左外边距设置为100px某些情况用这个设置 !important值无效
如果属性有’-号 ,就写成驼峰的形式(如textAlign) 如果想保留 - 号 ,就中括号的形式
element.style.height = 100px;2.直接设置属性
只能用于某些属性 ,相关样式会自动识别
element.setAttribute(height, 100); element.setAttribute(height, 100px);3.设置style的属性
element.setAttribute(style, height: 100px !important);4.使用setProperty
如果要设置!important ,推荐用这种方法设置第三个参数 element.style.setProperty(height, 300px, important);5.改变class (推荐)
通过改变伪元素父级的class来动态更改伪元素的样式 element.className = blue; element.className += blue fb;6.设置cssText
element.style.cssText = height: 100px !important; element.style.cssText += height: 100px !important;7.引入css样式文件
创建引入新的css样式文件 function addNewStyle(newStyle) { var styleElement = document.getElementById(styles_js); if (!styleElement) { styleElement = document.createElement(style); styleElement.type = text/css; styleElement.id = styles_js; document.getElementsByTagName(head)[0].appendChild(styleElement); } styleElement.appendChild(document.createTextNode(newStyle)); } addNewStyle(.box {height: 100px !important;});8.使用addRule 、insertRule
// 在原有样式操作 document.styleSheets[0].addRule(.box, height: 100px); document.styleSheets[0].insertRule(.box {height: 100px}, 0); // 或者插入新样式时操作 var styleEl = document.createElement(style), styleSheet = styleEl.sheet; styleSheet.addRule(.box, height: 100px); styleSheet.insertRule(.box {height: 100px}, 0); document.head.appendChild(styleEl);9 、通过classList控制样式
classList属性返回一个元素类属性集合(这里可以简单理解为类名的集合) ,通过使用classList中的方法可以方便的访问和控制元素类名 ,达到控制样式的目的classList常用方法介绍:
名称 描述 add(class1, class2, …) 添加一个或多个类名 remove(class1, class2, …) 移除一个或多个类名 replace(oldClass, newClass) 替换类名 contains(class) 判定类名是否存在,返回布尔值 toggle(class, true|false) 如果类名存在 ,则移除它 ,否则添加它,第二个参数代表无论类名是否存在 ,强制添加(true)或删除(false) <div class="box">classList test</div> <script> var box = document.querySelector(.box) box.classList.add(box1, box2) // [box] => [box, box1, box2] box.classList.remove(box1, box2) // [box, box1, box2] => [box] box.classList.replace(box, box2) // [box] => [box2] box.classList.contains(box1) // 当前元素不包含类名box1 ,返回false box.classList.toggle(active) // [box2] => [box2, active] </script>如果以上知识对你有用欢迎点赞和关注~ 谢谢~
声明:本站所有文章 ,如无特殊说明或标注 ,均为本站原创发布 。任何个人或组织 ,在未征得本站同意时 ,禁止复制 、盗用 、采集 、发布本站内容到任何网站 、书籍等各类媒体平台 。如若本站内容侵犯了原著者的合法权益 ,可联系我们进行处理 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!