Add inline style using Javascript

前端 未结 11 1150
悲&欢浪女
悲&欢浪女 2020-11-28 06:10

I\'m attempting to add this code to a dynamically created div element

style = \"width:330px;float:left;\" 

The code in which creates the dy

相关标签:
11条回答
  • 2020-11-28 06:39

    You can try with this

    nFilter.style.cssText = 'width:330px;float:left;';
    

    That should do it for you.

    0 讨论(0)
  • 2020-11-28 06:40

    you should make a css class .my_style then use .addClass('.mystyle')

    0 讨论(0)
  • 2020-11-28 06:41

    Do it with css now that you've created the class. .well { width:330px; float:left; }

    0 讨论(0)
  • 2020-11-28 06:43

    If you don't want to add each css property line by line, you can do something like this:

    document.body.insertAdjacentHTML('afterbegin','<div id="div"></div>');
    
    /**
     * Add styles to DOM element
     * @element DOM element
     * @styles object with css styles
     */
    function addStyles(element,styles){
      for(id in styles){
        element.style[id] = styles[id];
      }
    }
    
    // usage
    var nFilter = document.getElementById('div');
    var styles = {
      color: "red"
      ,width: "100px"
      ,height: "100px"
      ,display: "block"
      ,border: "1px solid blue"
    }
    addStyles(nFilter,styles);

    0 讨论(0)
  • 2020-11-28 06:46

    Use cssText

    nFilter.style.cssText +=';width:330px;float:left;';
    
    0 讨论(0)
提交回复
热议问题