How do you add CSS with Javascript?

前端 未结 14 2743
旧时难觅i
旧时难觅i 2020-11-22 17:18

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

14条回答
  •  余生分开走
    2020-11-22 18:03

    Here's a sample template to help you get started

    Requires 0 libraries and uses only javascript to inject both HTML and CSS.

    The function was borrowed from the user @Husky above

    Useful if you want to run a tampermonkey script and wanted to add a toggle overlay on a website (e.g. a note app for instance)

    // INJECTING THE HTML
    document.querySelector('body').innerHTML += '
    Hello World
    '; // CSS INJECTION FUNCTION //https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript function insertCss( code ) { var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { // IE style.styleSheet.cssText = code; } else { // Other browsers style.innerHTML = code; } document.getElementsByTagName("head")[0].appendChild( style ); } // INJECT THE CSS INTO FUNCTION // Write the css as you normally would... but treat it as strings and concatenate for multilines insertCss( "#injection {color :red; font-size: 30px;}" + "body {background-color: lightblue;}" )

提交回复
热议问题