js 样式操作
来源:互联网 发布:西科软件科技有限公司 编辑:程序博客网 时间:2024/05/29 15:53
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <link id="style" rel="stylesheet" href="test.css"> <style> .div1{ background-color:black; width:50px; height:50px; } .div2{ border:5px solid black; } </style> <style></style></head><body> <!--行内样式优先级最高--> <div id="div1" class="div2" style=" background-color:red; width:100px; height:100px; "></div> <script> var oDiv1 = document.getElementById("div1"); // 第一种改变样式的方法,一句只能改变一个属性,js里面用到css属性带“-”的首字母大写的方式表示 oDiv1.style.backgroundColor = "green"; oDiv1.style.width = "200px"; oDiv1.style.height = "200px"; // 第二种改变样式的方法,可以重写行内样式表,没有重写的就被删除了,在内嵌样式表和外部样式表的内容不会被改变 oDiv1.style.cssText = " background-color:yellow; width:300px; height:300px; "; // 上面两种方法,样式混在逻辑里,第三种改变样式的方法,通过添加className,要注意避免覆盖已有的class,优先级不如行内样式,所以效果没有呈现 oDiv1.className += " div1"; //第四种改变样式的方法,替换外部样式表,可以一次更改很多元素的样式 var oStyle = document.getElementById("style"); oStyle.href = "test_replace.css"; // 这么多种更改样式的方法,使用getComputedStyle实际应用的样式,返回一个CSSStyleDeclaration对象,里面包含了目标元素所有样式,IE9-使用currentStyle, var div_style = window.getComputedStyle(oDiv1); // var div_style = oDiv1.currentStyle; console.log(div_style.backgroundColor); console.log(div_style.width); console.log(div_style.height); // js创建一个外部样式表 function loadStyles(url){ var link = document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = url; var head = document.getElementsByTagName("head")[0]; head.appendChild(link); } loadStyles("style.css"); // 通过document.styleSheets获得应用于文档的所有样式表,包括link和style,不包括行内样式和动态替换和添加的外部样式表 var sheet = null; for( var i=0, len = document.styleSheets.length; i<len; i++){ sheet = document.styleSheets[i]; console.log(sheet.href); } // 可以获得替换后和动态添加的外部样式表 var link = document.getElementsByTagName("link"); for( var i=0, len = link.length; i<len; i++){ console.log(link[i].href); } </script></body></html>
0 0
- js 样式操作
- JS-操作样式
- js操作元素样式
- js css样式操作代码
- js 对于样式的操作
- js操作css样式(第十一课)
- JS操作CSS样式,获取与设置
- JS操作HTML元素的CSS样式
- JS中对样式的操作!
- js中css样式的操作
- js中巧用cssText属性批量操作样式
- 如何在js中操作样式
- js 针对html 元素 css样式 操作 等 累积
- 【JS总结】——DOM操作表格和样式
- js中巧用cssText属性批量操作样式(转)
- js样式
- 样式操作
- JS行间样式与非行间样式操作(及兼容性解决方法)
- window7 python2.7 安装scrapy
- POJ 1325-Machine Schedule(二分图匹配-匈牙利算法)
- C++ 重载运算符 友元函数
- html 表格
- 点击页面多次后,jdbc操作,抛数据库连接资源不足异常
- js 样式操作
- linux C++ 读写文件
- java 多线程 CountDownLatch用法
- datagrid getSelections只能获取一行
- 降低Java垃圾回收开销的5条建议
- CodeForces 670D Triangles
- iOS时间那些事
- 关于Pods written in Swift can only be integrated as frameworks问题的解决
- Android中的五种数据存储方式