• jacascript CSS样式的脚本化(js)操作


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

      引入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=" 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=" 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=" 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
            <script type="text/javascript">
                var oWrapper = document.getElementsByClassName('wrapper')[0];
                console.log(oWrapper.style.cssText);
                // 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=" 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; 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=" 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=" 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=" 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>
  • 相关阅读:
    资源文件 -- 初级应用篇
    Dephi中资源文件的应用
    VC++ 中使用内存映射文件处理大文件
    Delphi中正常窗口的实现
    让程序只运行一个实例
    多条明细(绑定到一个字段)汇总
    在更新之后最好有个判断 看是否更新上 编码码自动生成
    Delphi中有序型
    使用powerDesign画er图 并用 Database --->Generate Database ---> Genarate Script一次性将表结构的脚本导出来。
    .Net中的水晶报表
  • 原文地址:https://www.cnblogs.com/sspeng/p/6720828.html
Copyright © 2020-2023  润新知