无法将内联css分配给javascript元素

时间:2012-08-05 10:43:15

标签: javascript html css

我正在构建一个将div注入网站的代码。问题是我不能通过javascript分配css值,因为它们似乎不会在文档上发生(不是全部)。

以下是代码:

var barRoot = document.createElement('DIV'); 
barRoot.style.backgroundColor='#44AA44';
barRoot.style['height']='30px';
barRoot.style['width']='100%';
barRoot.style['position']='absolute';
barRoot.style['font-size']='14px';
barRoot.style['font-family']='Arial, Helvetica, sans-serif';
barRoot.style['z-index']='99999001';
barRoot.style['font-weight']='bold';
barRoot.style['top']='0pt';
barRoot.style['left']='0pt';
barRoot.style['color']='White';
barRoot.style['padding']='0pt';
barRoot.style['margin']='0pt';
barRoot.style['border']='0px solid rgb(0, 0, 0)';
barRoot.id =  'irobRootElem1';  
document.body.insertBefore(barRoot, document.body.firstChild);  

var heartImg = document.createElement('IMG');   
heartImg.src = 'heart.png';  
heartImg.style['float']='left';  
heartImg.style['margin-left']='8px';  
heartImg.style['margin-top']='5px';  
heartImg.style['margin-right']='8px';  
barRoot.appendChild(heartImg);  

2 个答案:

答案 0 :(得分:0)

如果您想通过JavaScript分配样式,则属性名称与CSS文件中的属性名称不完全相同。

检查this list in the w3c doc

但正如所建议的,使用 比编程设置样式更容易

以下是从上面的w3链接中提取的列表:

  

文档对象模型(DOM)级别2样式规范

     

版本1.0

     

W3C 2000年11月13日建议书

azimuth
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
border
borderCollapse
borderColor
borderSpacing
borderStyle
borderTop
borderRight
borderBottom
borderLeft
borderTopColor
borderRightColor
borderBottomColor
borderLeftColor
borderTopStyle
borderRightStyle
borderBottomStyle
borderLeftStyle
borderTopWidth
borderRightWidth
borderBottomWidth
borderLeftWidth
borderWidth
bottom
captionSide
clear
clip
color
content
counterIncrement
counterReset
cue
cueAfter
cueBefore
cursor
direction
display
elevation
emptyCells
cssFloat
font
fontFamily
fontSize
fontSizeAdjust
fontStretch
fontStyle
fontVariant
fontWeight
height
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginTop
marginRight
marginBottom
marginLeft
markerOffset
marks
maxHeight
maxWidth
minHeight
minWidth
orphans
outline
outlineColor
outlineStyle
outlineWidth
overflow
padding
paddingTop
paddingRight
paddingBottom
paddingLeft
page
pageBreakAfter
pageBreakBefore
pageBreakInside
pause
pauseAfter
pauseBefore
pitch
pitchRange
playDuring
position
quotes
richness
right
size
speak
speakHeader
speakNumeral
speakPunctuation
speechRate
stress
tableLayout
textAlign
textDecoration
textIndent
textShadow
textTransform
top
unicodeBidi
verticalAlign
visibility
voiceFamily
volume
whiteSpace
widows
width
wordSpacing
zIndex

答案 1 :(得分:0)

我会添加样式标记。使用setAttribute设置内联样式。