前言:这是笔者学习之后自己的理解与整理。如果有错误或者疑问的地方,请大家指正,我会持续更新!

  引入CSS有3种方式:行间样式,内联样式和外部链接样式。

  在实际工作中,我们使用 javascript 操作CSS样式时:

  1. 在改变元素的单个样式时,一般会直接操作,改变其行间样式;如:obj.style.color=...
  2. 同时改变元素的较多样式时,可以使用 cssText,改变其行间样式;obj.style.cssText=...
  3. 更常用的是使用 css 类,将更改前和更改后的样式提前设置为类 。只要更改其类名 className 即可,obj.className;
  4. 如果要改变多个类名,使用 classList 更为方便,IE9及以下浏览器不支持;

行间样式

  行间样式又叫内联样式,element 元素节点提供 style 属性,用来操作 CSS 行间样式;

  如果一个 CSS 属性名包含一个或多个连字符,属性名的格式应该是移除连字符,将每个连字符后面紧接着的字母大写(驼峰命名法);

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
<script type="text/javascript">
var oWrapper = document.getElementsByClassName('wrapper')[0];
console.log(oWrapper.style.borderBottom);//10px solid rgb(255, 255, 0)
</script>

  其实,如果操作行间样式,可以使用元素节点的属性操作方法 hasAttribute()、getAttribute()、setAttribute()、removeAttribute() 等,来操作style属性;

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
<script type="text/javascript">
var oWrapper = document.getElementsByClassName('wrapper')[0];
oWrapper.setAttribute('style','background-color: #0ff;')
//setAttribute 设置的是当前属性的整体
console.log(oWrapper.hasAttribute('style'));//true
console.log(oWrapper.getAttribute('style'));//background-color: #0ff;
</script>

cssText

  通过 cssText 属性能够访问到 style 属性中的CSS代码(行间样式);

  在读模式下,cssText 返回浏览器对 style 属性中的CSS代码的内部表示;IE8及以下浏览器返回的属性名是全大写的

  在写模式中,赋给 cssText 的值会重写整个 style 属性的值;

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
<script type="text/javascript">
var oWrapper = document.getElementsByClassName('wrapper')[0];
console.log(oWrapper.style.cssText);
//width: 500px; height: 200px; border-bottom: 10px solid rgb(255, 255, 0); oWrapper.style.cssText = 'background-color: #0ff;';
console.log(oWrapper.style.cssText);//background-color: rgb(0, 255, 255);
</script>

length

  length 属性返回内联样式中的样式个数;IE8及以下浏览器不支持;

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
<script type="text/javascript">
var oWrapper = document.getElementsByClassName('wrapper')[0];
console.log(oWrapper.style.length);//5
//width height border-bottom-width border-bottom-style border-bottom-color
</script>

方法

  getPropertyPriority(propertyName) 如果给定的属性使用了!important设置,则返回"important";否则返回空字符串;IE8及以下浏览器不支持

  setProperty(propertyName,value,priority) 方法将给定属性设置为相应的值,并加上优先级标志("important"或一个空字符串),该方法无返回值;IE8及以下浏览器不支持

  removeProperty(propertyName) 方法从样式中删除给定属性,并返回被删除属性的属性值;IE8及以下浏览器不支持

        <div id="test" style="height: 40px!important;width: 40px;background-color: pink;border:10px solid #f0f"></div>
<script>
var oTest = document.getElementById('test'); //getPropertyPriority() 如果给定的属性使用了!important设置,则返回"important";否则返回空字符串
console.log(oTest.style.getPropertyPriority('height'));//'important'
console.log(oTest.style.getPropertyPriority('width'));//'' //setProperty(propertyName,value,priority)方法将给定属性设置为相应的值,并加上优先级标志("important"或一个空字符串)
oTest.style.setProperty('width','100px');
console.log(oTest.style.width);//100px
console.log(oTest.style.getPropertyPriority('width'));//'' oTest.style.setProperty('background-color','blue','important');
console.log(oTest.style.backgroundColor);//blue
console.log(oTest.style.getPropertyPriority('background-color'));//important //removeProperty()方法从样式中删除给定属性,并返回被删除属性的属性值
console.log(oTest.style.border);//10px solid rgb(255, 0, 255)
oTest.style.removeProperty('border');
console.log(oTest.style.border);//''
</script>

计算样式

  元素的渲染结果是多个CSS样式博弈后的最终结果,这也是CSS中的C(cascade)层叠的含义。cssText 只能获取行间样式,这通常来说,并不是我们想要的结果,我们有时候需要的是元素的计算样式(无论行内、内联或链接);

  元素的计算样式(computedStyle)是一组在显示元素时实际使用的属性值,也是用一个 CSSStyleDeclaration 对象来表示的,但实际样式是只读的,主要通过getComputedStyle() 方法实现;IE8及以下浏览器不支持

  getComputedStyle() 方法接收两个参数:要取得计算样式的元素和一个伪元素字符串。如果不需要伪元素信息,第二个参数可以是 null。getComputedStyle() 方法返回一个 CSSStyleDeclaration 对象,其中包含当前元素的所有计算的样式; 

  第二个参数代表伪元素字符串,包括":before"、":after"、":first-line"等,如果设置为null或省略不写,则返回自身元素的 CSSStyleDeclaration 对象;

  对于font、background、border等复合样式,各浏览器处理不一样。chrome 会返回整个复合样式,而IE9+、firefox和safari则输出空字符串'';

  在计算样式中,类似百分比等相对单位会转换为绝对值;

        <style type="text/css">
#test{
background-color: #ff0;
}
#test:before{
content: "";
width: 50px;
display: block;
}
</style>
<div id="test" style="width: 100px;height: 200px;"></div>
<script type="text/javascript">
var oTest = document.getElementById('test'); console.log(getComputedStyle(oTest).width);//100px
console.log(getComputedStyle(oTest).height);//200px console.log(getComputedStyle(oTest).backgroundColor);//rgb(255, 255, 0) console.log(getComputedStyle(oTest,':before').width);//50px
</script>

  IE8及以下浏览器不支持 getComputedStyle() 方法,但在 IE 中每个具有 style 属性的元素有一个 currentStyle 属性,这个属性是 CSSStyleDeclaration 的实例,包含当前元素全部计算后的样式;

  obj.currentStyle[style] 属性中的计算样式并不会输出集合样式,对颜色、百分比设置不会进行相应转换,而是原样输出;

        <style type="text/css">
#test{
background-color: #ff0;
}
</style>
<div id="test" style="width: 30%;height: 200px;"></div>
<script type="text/javascript">
var oTest = document.getElementById('test'); //标准浏览器会报错,IE正常显示
console.log(oTest.currentStyle.backgroundColor);//#ff0
console.log(oTest.currentStyle.width);//30%
console.log(oTest.currentStyle.height);//200px
</script>

兼容性写法

        <style type="text/css">
#test{
background-color: #ff0;
}
</style><div id="test" style="width: 30%;height: 200px;"></div>
<script type="text/javascript">
function getCSS(obj,attribute){
return window.getComputedStyle ? getComputedStyle(obj)[attribute] : obj.currentStyle[attribute];
} var oTest = document.getElementById('test');
console.log(getCSS(oTest,'width'));//计算出来的绝对值
console.log(getCSS(oTest,'height'));//200px
</script>

动态样式

  动态样式包括两种情况:一种是通过<link>元素插入外部样式表,另一种是通过<style>元素插入内部样式。

        <script type="text/javascript">
//动态加载外部样式
function loadLinkCSS(urlData){
loadLinkCSS.mark = 'load';//标记是否执行过此程序
var linkCSS = document.createElement("link");
linkCSS.rel = "stylesheet";
linkCSS.type = "text/css";
linkCSS.href = urlData;//路径设置
var oHead = document.getElementsByTagName('head')[0];
oHead.appendChild(linkCSS);
} //动态加载内部样式
//该方法在IE8及以下浏览器中报错,因为IE8及以下浏览器将<style>视为当作特殊的节点,不允许访问其子节点或设置 innerHTML 属性
function loadStyleCSS(str){
loadStyleCSS.mark = 'load';//标记是否执行过此程序
var styleCSS = document.createElement("style");
styleCSS.type = "text/css";
styleCSS.innerHTML = str;
var head = document.getElementsByTagName('head')[0];
head.appendChild(styleCSS);
}
</script>

  

  动态插入内部样式时,存在兼容问题,有两种兼容处理办法:

  1. IE浏览器支持访问并修改元素的 CSSStyleSheet 对象的 cssText 属性,通过修改该属性可实现类似效果;
  2. 作用域元素是微软自己的一个定义。在IE8及以下浏览器中,<style>元素是一个没有作用域的元素,如果通过 innerHTML 插入的字符串开头就是一个无作用域的元素,那么IE8及以下浏览器会在解析这个字符串前先删除该元素;
        <script type="text/javascript">
//动态加载内部样式的兼容性写法一
//IE浏览器支持访问并修改元素的 CSSStyleSheet 对象的 cssText 属性,通过修改该属性可实现类似效果
function loadStyleCssCompatA(str){
loadStyleCssCompatA.mark = 'load';//标记是否执行过此程序
var styleCSS = document.createElement("style");
styleCSS.type = "text/css";
try{
styleCSS.innerHTML = str;
}catch(ex){
styleCSS.styleSheet.cssText = str;
}
var head = document.getElementsByTagName('head')[0];
head.appendChild(styleCSS);
} //动态加载内部样式的兼容性写法二
   //在IE8及以下浏览器中,style元素是一个没有作用域的元素,
//如果通过 innerHTML 插入的字符串开头就是一个无作用域的元素,那么IE8及以下浏览器会在解析这个字符串前先删除该元素
function loadStyleCssCompatB(str){
loadStyleCssCompatB.mark = 'load';
var styleCSS = document.createElement("div");
styleCSS.innerHTML = '_' + '<style>' + str+'</style>';
styleCSS.removeChild(div.firstChild);
var oHead = document.getElementsByTagName('head')[0];
oHead.appendChild(styleCSS.firstChild);
styleCSS = null;
}
</script>

CSS模块侦测

  CSS的规则发展太快,新的模块层出不穷。不同浏览器的不同版本,对CSS模块的支持情况都不一样。有时候,需要知道当前浏览器是否支持某个模块,这就叫做"CSS模块的侦测";

  一个比较普遍适用的方法是,判断某个DOM元素的 style 对象的某个属性值是否为字符串。如果该CSS属性确实存在,会返回一个字符串。即使该属性实际上并未设置,也会返回一个空字符串。如果该属性不存在,则会返回 undefined

  CSS.supports() 方法返回一个布尔值,表示是否支持某条CSS规则;safari 和 IE浏览器不支持

        <div id="test"></div>
<script>
var oTest = document.getElementById('test'); //CSS模块的侦测
//IE9及以下浏览器和safari返回undefined,其他浏览器都返回'',
//所以IE9及以下浏览器和safari不支持animation
console.log(oTest.style.animation); //IE和firefox浏览器返回undefined,chrome和safari浏览器都返回'',
//所以IE和firefox浏览器不支持WebkitAnimation
console.log(oTest.style.WebkitAnimation); //safari和IE浏览器不支持,
//chrome返回true
console.log(CSS.supports('transition','1s'));//true
</script>

jacascript CSS样式的脚本化(js)操作的更多相关文章

  1. jacascript CSS样式的脚本化操作

    前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 引入CSS有3种方式:行间样式,内联样式和外部链接样式. 在实际工作中,我们使用 javascript 操 ...

  2. jq选择器(jq 与 js 互相转换),jq操作css样式 / 文本内容, jq操作类名,jq操作全局属性,jq获取盒子信息,jq获取位置信息

    jq选择器(jq 与 js 互相转换) // 获取所有的页面元素jq对象 $('css3选择器语法'); var $box = $(".box:nth-child(1)"); 获取 ...

  3. html css javascript 知识点总结 bom js 操作标签 文本 节点 表格各行变色 悬停变色 省市联动 正则

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  4. asp.net通过后台代码给前台设置css样式,下拉列表在js中的取值

    后台根据不同的用户登陆隐藏或显示前台div标签 前台: 将div声明成服务器端控件 <div id="div1" runat="server">.. ...

  5. abp架构中加载公共css样式表和公共js的文件目录位置

    src\shared\helpers\LocalizedResourcesHelper.ts

  6. 深入理解脚本化CSS系列第四篇——脚本化样式表

    × 目录 [1]CSSStyleSheet [2]CSSRule 前面的话 关于脚本化CSS,查询样式时,查询的是计算样式:设置单个样式时,设置的是行间样式:设置多个样式时,设置的是CSS类名.脚本化 ...

  7. 前端(十二)—— JavaScript基础操作:if语句、for循环、while循环、for...in、for...of、异常处理、函数、事件、JS选择器、JS操作页面样式

    JavaScript基础操作 一.分支结构 1.if语句 if 基础语法 if (条件表达式) { 代码块; } // 当条件表达式结果为true,会执行代码块:反之不执行 // 条件表达式可以为普通 ...

  8. 利用JS脚本通过getAttribute()和setAttribute()等对CSS样式进行操作

    HTML中引入CSS样式的方式有三种: 1.最常用的,引入样式表,在样式表中编写样式,引入方式如下:<link href="css/style.css" rel=" ...

  9. 深入理解脚本化CSS系列第一篇——脚本化行内样式

    × 目录 [1]用法 [2]属性 [3]方法 前面的话 脚本化CSS,通俗点说,就是使用javascript来操作CSS.引入CSS有3种方式:外部样式,内部样式和行间样式.本文将主要介绍脚本化行间样 ...

随机推荐

  1. JavaWeb基础知识

    一.WEB基本概念 1.1.WEB开发的相关知识 WEB,在英语中web即表示网页的意思,它用于表示Internet主机上供外界访问的资源. Internet上供外界访问的Web资源分为: 静态web ...

  2. qt 添加本程序的注册表项

    QStringcmd; cmd.clear(); QStringapplication_path=QCoreApplication::applicationFilePath();//带文件扩展名的全路 ...

  3. git常见问题之git pull时Please specify which branch you want to merge with.

    $ git pull时遇到如下提示 $ git pull warning: no common commits remote: Counting objects: 5, done. remote: C ...

  4. Matrix: android 中的Matrix (android.graphics.Matrix) (转)

    本篇博客主要讲解一下如何处理对一个Bitmap对象进行处理,包括:缩放.旋转.位移.倾斜等.在最后将以一个简单的Demo来演示图片特效的变换. 1. Matrix概述 对于一个图片变换的处理,需要Ma ...

  5. i18n 语言码和对应的语言库

    语言码 语言名称 af Afrikaans am Amharic ar Arabic az Azerbaijani be Belarusian bg Bulgarian bh Bihari bn Be ...

  6. ThinkPhp5 mongodb 使用自定义objectID出错解决

    在Tp5中使用mongodb 使用自定义ObjectId时报错:Cannot use object of type MongoDB\\BSON\\ObjectID as array 查询源码发现在to ...

  7. osg Shader 着色器

    #ifdef _WIN32 #include <Windows.h> #endif // _WIN32 #include <osg/Group> #include <os ...

  8. Github排名靠前的iOS库

    //iOS第三方开源库的吐槽和备忘 http://blog.ibireme.com/2013/09/23/ios-third-party-libs/#more-41361 //整理了一份Github上 ...

  9. avro-1.8.1 serialize BigDecimal and Short error fix.

    1. create mysql table like CREATE TABLE `test` ( `a` ) ', `b` ,) DEFAULT NULL, `c` ,) DEFAULT NULL ) ...

  10. MySQL创建及删除临时表

    示例SQL: drop temporary table if exists testdb.tmp_test_table; create temporary table testdb.tmp_test_ ...