回答:
一般に、CSSプロパティはダッシュなしでキャメルケースにすることでJavaScriptに変換されます。そうbackground-color
なりましたbackgroundColor
。
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
CSSですべてのスタイルなどを保持し、JavaScriptでクラス名を設定または設定解除するだけで、コードの保守性が向上する場合があります。
あなたのCSSは明らかに次のようなものになります:
.highlight {
background:#ff00aa;
}
次にJavaScriptで:
element.className = element.className === 'highlight' ? '' : 'highlight';
または、小さなjQueryを使用します。
$('#fieldID').css('background-color', '#FF6600');
次のスクリプト要素をbody要素に追加します。
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>
var element = document.getElementById('element');
element.onclick = function() {
element.classList.add('backGroundColor');
setTimeout(function() {
element.classList.remove('backGroundColor');
}, 2000);
};
.backGroundColor {
background-color: green;
}
<div id="element">Click Me</div>
あなたはこれを試すことができます
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
例。
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
は有効なJavaScriptではありません。これが、CSSプロパティがCamelCaseに変換される理由です。
KISS回答:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$('#ID / .Class').css('background-color', '#FF6600');
jqueryを使用することにより、要素のクラスまたはIDをターゲットにして、CSS背景またはその他のスタイルを適用できます
あなたは使うことができます
$('#elementID').css('background-color', '#C0C0C0');
JavaScript:
document.getElementById("ID").style.background = "colorName"; //JS ID
document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class
jquery:
$('#ID/.className').css("background","colorName") // One style
$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
HTMLElement
JavaScriptを使用してほとんどのCSSプロパティを変更できます。次のステートメントを使用します。
document.querySelector(<selector>).style[<property>] = <new style>
どこ<selector>
、<property>
、<new style>
すべてのあるString
オブジェクトが。
通常、スタイルプロパティはCSSで使用される実際の名前と同じ名前になります。ただし、1つ以上の単語がある場合は、キャメルケースになります。たとえば、background-color
で変更されbackgroundColor
ます。
次のステートメントは、背景を#container
赤に設定します。
documentquerySelector('#container').style.background = 'red'
ここでは、0.5秒ごとにボックスの色を変更する簡単なデモを示します。
colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']
let i = 0
setInterval(() => {
const random = Math.floor(Math.random()*colors.length)
document.querySelector('.box').style.background = colors[random];
}, 500)
.box {
width: 100px;
height: 100px;
}
<div class="box"></div>
HTMLElement
CSSスタイルを複数の要素に適用することを想像してください。たとえば、クラス名を持つすべての要素の背景色を作成しますbox
lightgreen
。次に、次のことができます。
要素を選択し、構造化.querySelectorAll
解除構文Array
を使用してオブジェクトに展開します。
const elements = [...document.querySelectorAll('.box')]
で配列をループし、.forEach
各要素に変更を適用します。
elements.forEach(element => element.style.background = 'lightgreen')
ここにデモがあります:
const elements = [...document.querySelectorAll('.box')]
elements.forEach(element => element.style.background = 'lightgreen')
.box {
height: 100px;
width: 100px;
display: inline-block;
margin: 10px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
要素の複数のスタイルプロパティを複数回変更する場合は、別の方法を使用することを検討できます。この要素を別のクラスにリンクしてください。
CSSで事前にスタイルを準備できるとするとclassList
、要素のにアクセスしてtoggle
関数を呼び出すことにより、クラスを切り替えることができます。
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
完全なリストは次のとおりです。
alignContent
alignItems
alignSelf
animation
animationDelay
animationDirection
animationDuration
animationFillMode
animationIterationCount
animationName
animationTimingFunction
animationPlayState
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
backgroundClip
backgroundOrigin
backgroundSize</a></td>
backfaceVisibility
borderBottom
borderBottomColor
borderBottomLeftRadius
borderBottomRightRadius
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderImage
borderImageOutset
borderImageRepeat
borderImageSlice
borderImageSource
borderImageWidth
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRadius
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopLeftRadius
borderTopRightRadius
borderTopStyle
borderTopWidth
borderWidth
bottom
boxShadow
boxSizing
captionSide
clear
clip
color
columnCount
columnFill
columnGap
columnRule
columnRuleColor
columnRuleStyle
columnRuleWidth
columns
columnSpan
columnWidth
counterIncrement
counterReset
cursor
direction
display
emptyCells
filter
flex
flexBasis
flexDirection
flexFlow
flexGrow
flexShrink
flexWrap
content
fontStretch
hangingPunctuation
height
hyphens
icon
imageOrientation
navDown
navIndex
navLeft
navRight
navUp>
cssFloat
font
fontFamily
fontSize
fontStyle
fontVariant
fontWeight
fontSizeAdjust
justifyContent
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
opacity
order
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
pageBreakAfter
pageBreakBefore
pageBreakInside
perspective
perspectiveOrigin
position
quotes
resize
right
tableLayout
tabSize
textAlign
textAlignLast
textDecoration
textDecorationColor
textDecorationLine
textDecorationStyle
textIndent
textOverflow
textShadow
textTransform
textJustify
top
transform
transformOrigin
transformStyle
transition
transitionProperty
transitionDuration
transitionTimingFunction
transitionDelay
unicodeBidi
userSelect
verticalAlign
visibility
voiceBalance
voiceDuration
voicePitch
voicePitchRange
voiceRate
voiceStress
voiceVolume
whiteSpace
width
wordBreak
wordSpacing
wordWrap
widows
writingMode
zIndex
$(".class")[0].style.background = "blue";