• JavaScript的DOM_通过元素的class属性操作样式


    使用 style 属性可以设置行内的 CSS 样式,而通过 id 和 class 调用是最常用的方法。

    <script type="text/javascript">
        window.onload = function(){
            var box = document.getElementById('box');
            box.id='pox';        //交换id之后,就会加载那个id的样式,但是这么做会引发各种怪异的现象 把 ID 改变会带来灾难性的问题
        }
    </script>
    <style type="text/css">
        #box{
            font-size:20px;
            color:red;
            background:#ccc;
        }
        #pox{
            font-size:30px;
            color:blue;
            background:orange;
        }
    </style>
    </head>
    <body>
        <div id="box">测试Div</div>
    </body>

      不建议通过变换id来改变CSS样式,可以通过class来改变

    <script type="text/javascript">
        window.onload = function(){
            var box = document.getElementById('box');
            box.className='bbb';
        }
    </script>
    <style type="text/css">
        .aaa{
            font-size:20px;
            color:red;
            background:#ccc;
        }
        .bbb{
            font-size:30px;
            color:blue;
            background:orange;
        }
    </style>
    </head>
    <body>
        <div id="box" class="aaa">测试Div</div>
    </body>

      在添加 className 的时候,我们想给一个元素添加多个 class 是没有办法的,后面一个必将覆盖掉前面一个,所以必须来写个函数:

    <script type="text/javascript">
        window.onload = function(){
            var box = document.getElementById('box');
            addClass(box,'bbb');
            addClass(box,'ccc');
            
            //判断是否存在这个 class
            function hasClass(element, className) {
                return element.className.match(new RegExp('(\s|^)'+className+'(\s|$)'));
            }
            //添加一个 class,如果不存在的话
            function addClass(element, className) {
                if (!hasClass(element, className)) {
                    element.className += " "+className;
                }
            }
            //删除一个 class,如果存在的话
            function removeClass(element, className) {
                if (hasClass(element, className)) {
                    element.className = element.className.replace(
                        new RegExp('(\s|^)'+className+'(\s|$)'),' ');
                }
            }
        } 
    </script>
    <style type="text/css">
        .aaa{
            font-size:20px;
            color:red;
            background:#ccc;
        }
        .bbb{
            font-size:30px;
            color:blue;
            background:orange;
        }
        .ccc{
            float:right;
        }
    </style>
    </head>
    <body>
        <div id="box" class="aaa">测试Div</div>
    </body>
  • 相关阅读:
    从服务器角度分析RPG游戏——NPC的AI
    羽翼特效设计
    坐骑特效设计(二)
    坐骑特效设计
    Unity AssetBundle打包资源工具
    有趣的进度条
    原生与组件
    bower
    yeoman
    grunt+bower+yo
  • 原文地址:https://www.cnblogs.com/LO-ME/p/4590134.html
Copyright © 2020-2023  润新知