P05 className

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div1{
            width: 100px;
            height: 100px;
            border: 1px solid black ;
        }
        .box{
            background: red;
        }
    </style>
    <script>
        function toRed(){
            var oBox = document.getElementById('div1');
            oBox.className='box';
        }
    </script>
</head>
<body>
    <input type="button" value="变红" onclick="toRed()">
    <div id="div1"></div>
</body>
</html>

上面的代码,是为了演示在JS中的一个特殊的情况:

  关于标签的属性的写法,一般情况下是在HTML中怎么写,在JS中就是怎么写的。

  但是有一种例外的情况就是,当属性名是保留字(关键字,如class),这个时候就不能直接写成属性名。

  以标签中的class属性为例,在JS中编写的时候,应该是className。否则代码是错误的,无法正确执行。

posted @ 2020-05-08 21:50  Runmoxin  阅读(87)  评论(0编辑  收藏  举报