如何将现有CSS类样式应用于动态创建的div? [英] How can I apply an existing CSS class style to a dynamically created div?

查看:52
本文介绍了如何将现有CSS类样式应用于动态创建的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为这个看似多余的问题道歉,但其他人似乎都在问不同的情况,例如使用JQuery.我正在尝试动态创建div&将现有的CSS样式应用于该样式,但div不会采用该样式.任何提示都将不胜感激:

 < style>分度{位置:绝对;溢出:隐藏;背景:rgba(1,1,0,1);宽度:400像素;高度:400px;}.a {左:2厘米;顶部:2厘米;z索引:1;}.b {左:4厘米;顶部:4厘米;z索引:2;}</style></head><身体>< script type ="text/javascript">createLayer(1);函数createLayer(layerIndex){var div = document.createElement('div');div.id ="div" + layerIndex;div.class ="tile a";document.body.appendChild(div);var canvas = document.createElement('canvas');canvas.id ="layer" + layerIndex;div.appendChild(canvas);} 

解决方案

在香草JS中,用于向元素添加类的属性是 className 而不是 class .

尝试以下方法:

div.className ="tile a";

Apologies for this seemingly redundant question, but the others all seem to be asking about different cases, such as using JQuery. I'm trying to dynamically create a div & apply an existing CSS style to it, but the div isn't taking on the style. Any tips are much appreciated:

    <style>
        div.tile {
            position: absolute;
            overflow: hidden;
            background:  rgba(1,1,0,1);
            width: 400px;
            height: 400px;
        }
        .a { left: 2cm; top: 2cm; z-index: 1; }
        .b { left: 4cm; top: 4cm; z-index: 2; }
    </style>
</head>
<body>
    <script type="text/javascript">

        createLayer(1);

        function createLayer(layerIndex){
            var div = document.createElement('div');
            div.id = "div"+layerIndex;
            div.class = "tile a";
            document.body.appendChild(div);
            var canvas = document.createElement('canvas');
            canvas.id     = "layer" + layerIndex;
            div.appendChild(canvas);
        }

解决方案

In vanilla JS the property for adding a class to an element is className not class.

Try this instead:

div.className = "tile a";

这篇关于如何将现有CSS类样式应用于动态创建的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆