如何使用 JavaScript 加载 CSS 规则

how to load css rules using javascript?

本文关键字:CSS 规则 加载 JavaScript 何使用      更新时间:2023-09-26

我目前正在使用 Vert.x。我可以轻松加载所需的js文件,但是当涉及到CSS时,没有任何内容加载。所以我想我最后的手段是编写一些 js 来设置这些 css 规则(超级最后的手段是将 css 写入 html 文件中)。

有没有好方法可以做到这一点?我在想这样的事情:

function loadIndexCss()
{
    document.getElementById("p2").style.color="blue";
    document.getElementById("p2").style.fontFamily="Arial";
    document.getElementById("p2").style.fontSize="larger";
}

将其保存在文件中,然后:

<script type="text/javascript" src="../css/css.js"></script>
<body onload="loadIndexCss()">
    <form id='frm_login'>
        <fieldset >
            <legend>Admin Login</legend>
            <label for='u' >Username: </label>
            <input type='text' name='username' id='u' maxlength="25" class="blocky"/>
            <label for='p' >Password:  </label>
            <input type='password' name='password' id='p' maxlength="25" class="blocky"/>
            <br/>
            <input type='button' name='Login' value='Login' id="btn_login" />
        </fieldset>
    </form>
</body>

这还能行吗? 如果这很愚蠢,请教:)

是的,这应该有效。您也可以以肮脏的方式执行此操作,创建命名样式标签:

<style id="sty"></style>

然后添加 CSS:

 document.getElementById("sty").innerHTML = "a {color: blue}";