Add inline style using Javascript

前端 未结 11 1149
悲&欢浪女
悲&欢浪女 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:22

    A few people have an example using setAttribute which I like. However it assumes you don't have any styles currently set. I would maybe do something like:

    nFilter.setAttribute('style', nFilter.getAttribute('style') + ';width:330px;float:left;');
    

    Or make it into a helper function like this:

    function setStyle(el, css){
      el.setAttribute('style', el.getAttribute('style') + ';' + css);
    }
    
    setStyle(nFilter, 'width:330px;float:left;');
    

    This makes sure that you can add styles to it continuously and it won't remove any style currently set by always appending to the current styles. It also adds an extra semi colon so that if there is a style ever missing one it will append another to make sure it is fully delimited.

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

    You can do it directly on the style:

    var nFilter = document.createElement('div');
    nFilter.className = 'well';
    nFilter.innerHTML = '<label>'+sSearchStr+'</label>';
    
    // Css styling
    nFilter.style.width = "330px";
    nFilter.style.float = "left";
    
    // or
    nFilter.setAttribute("style", "width:330px;float:left;");
    
    0 讨论(0)
  • 2020-11-28 06:27
    var div = document.createElement('div');
    div.setAttribute('style', 'width:330px; float:left');
    div.setAttribute('class', 'well');
    var label = document.createElement('label');
    label.innerHTML = 'YOUR TEXT HERE';
    div.appendChild(label);
    
    0 讨论(0)
  • 2020-11-28 06:30

    Using jQuery :

    $(nFilter).attr("style","whatever");
    

    Otherwise :

    nFilter.setAttribute("style", "whatever");
    

    should work

    0 讨论(0)
  • 2020-11-28 06:36
    nFilter.style.width = '330px';
    nFilter.style.float = 'left';
    

    This should add an inline style to the element.

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

    Try something like this

    document.getElementById("vid-holder").style.width=300 + "px";
    
    0 讨论(0)
提交回复
热议问题