Dynamically add css to page via javascript

前端 未结 5 1527
旧巷少年郎
旧巷少年郎 2020-12-04 16:33

I\'m making a widget that will be added to external websites, and I have made a page that generates css for them to style it (text color, background color, font size, etc).

相关标签:
5条回答
  • 2020-12-04 16:43

    Can you add a style tag to the DOM, with the contents of the text-area in it? You may want to give it an id so you can change it later.

    0 讨论(0)
  • 2020-12-04 16:57

    I have traditionally appended a <style> block when doing elements.

    var style_rules = [];
    
    style_rules.push("#" + myElemId + " { /* Rules */ } ");
    /* ... */
    
    var style = '<style type="text/css">' + style_rules.join("\n") + "</style>";
    $("head").append(style);
    

    An important thing to note is that because you don't know what any of the existing styles is, or what id's might conflict on the page, it's very useful to keep track of your id's inside your JavaScript application, then using those to populate the injected <style> block. I also tend to run my names through a prefix function to ensure that the generic names of wrapper, and unit do not conflict (they are turned into something like myunique_wrapper and myunique_unit.

    Incorporating a basic CSS reset like #myWrapper {margin: 0; padding: 0} can be a decent starting platform for building your own custom styles.

    Addressing your unique case, a live preview so to speak, I would designate a div with standard elements. Then when they click "update" read in the rules and append them to the head. If you want to negate any residual effects from past rules you can remove the last <style> element or better yet give your <style> element an id. I'm not sure if that kind of selection would work, but it should.

    0 讨论(0)
  • 2020-12-04 16:57
    var element = document.createElement('style');
    element.setAttribute('type', 'text/css');
    
    if ('textContent' in element) {
      element.textContent = css;
    } else {
      element.styleSheet.cssText = css;
    }
    
    document.getElementsByTagName('head')[0].appendChild(element);
    
    0 讨论(0)
  • 2020-12-04 16:58

    if you want to add css text

    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = 'content';
    document.getElementsByTagName('head')[0].appendChild(style);
    

    if you want to add css file

    var link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('type', 'text/css');
    link.setAttribute('href', 'css/my.css');
    document.getElementsByTagName('head')[0].appendChild(link);
    
    0 讨论(0)
  • 2020-12-04 17:06

    I recommend you start using a decent framework for your web/JavaScript development, personally I'd go with jQuery.

    http://api.jquery.com/css/
    

    There are some code snippets here that show you how to quickly set css properties for elements.

    0 讨论(0)
提交回复
热议问题