使用Javascript添加内联样式

122
我试图将这段代码添加到一个动态创建的div元素中。
style = "width:330px;float:left;" 

创建动态

的代码是:

var nFilter = document.createElement('div');
nFilter.className = 'well';
nFilter.innerHTML = '<label>' + sSearchStr + '</label>';

我的想法是在 <div class="well" 之后添加样式,但我不知道该怎么做。


1
有什么区别呢?内联样式始终具有最高的特异性。 - Amberlamps
因为 div 是动态创建的,所以我不能使用静态代码,因为它是一个完整的 JavaScript 库脚本。 - Curtis Crewe
也许这是一个 XY 问题。你想要实现什么?nFilter.style.width = '330px'; nFilter.style.float = 'left'; 是你正在寻找的吗? - Amberlamps
11个回答

157
nFilter.style.width = '330px';
nFilter.style.float = 'left';

这应该会为元素添加内联样式。


53

你可以直接在样式中完成它:

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;");

7
不是CSS样式,而是使用setAttribute的第三个选项对我非常完美地起到了作用。 - milkersarac

25

使用jQuery:

$(nFilter).attr("style","whatever");
否则:
nFilter.setAttribute("style", "whatever");

应该可以工作


6
这种情况下不必使用JQuery。 - Dharman
13
他提供了一个没有使用 JQuery 的替代方案。不需要给他点踩。 - Termato

17

你可以尝试这个

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

那就应该能满足你的需求了。


13

有些人使用setAttribute的示例我很喜欢。但是它假设您当前没有设置任何样式。我可能会这样做:

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

或者将其制作成一个如下所示的辅助函数:

function setStyle(el, css){
  el.setAttribute('style', el.getAttribute('style') + ';' + css);
}

setStyle(nFilter, 'width:330px;float:left;');

这样可以确保您可以持续添加样式,而不会移除当前设置的任何样式,因为它始终将其附加到当前样式上。它还添加了一个额外的分号,以便如果样式缺少一个分号,它将附加另一个分号以确保完全分隔。


13
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);

6
如果您不想逐行添加每个CSS属性,可以尝试以下方法:

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);


这太酷了,它帮助我大大地整理了我的纯HTML CSS代码,没有框架。非常感谢! - jellytran

4

你应该创建一个CSS类 .my_style,然后使用 .addClass('.mystyle')


我使用 element.classList.add("myClass"),它有效,这是你想要的吗?相比其他解决方案,它使我的源代码更易于维护和理解。 - gouessej

1
尝试一些类似这样的内容。
document.getElementById("vid-holder").style.width=300 + "px";

1
使用 cssText
nFilter.style.cssText +=';width:330px;float:left;';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接