JavaScriptを使用してHTMLのCSS背景色を設定する方法


回答:


155

一般に、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');

3
色を追加したいのですが、明らかに引用符で囲む必要がありますelement.style.backgroundColor = "color"; 例-element.style.backgroundColor = "orange"; 優れた回答
Catto

Seleniumテストでは:((IJavaScriptExecutor)WebDriver).ExecuteScript( "arguments [0] .style.background = 'yellow';"、webElement);
ネクソマ2018年

@Cattoこの場合、色は関数の引数であるため、引用符で囲む必要はありません。ただし、通常、JSで色を設定する場合は二重引用符が必要です。
Bharat Mallapur 2018年

29

CSSですべてのスタイルなどを保持し、JavaScriptでクラス名を設定または設定解除するだけで、コードの保守性が向上する場合があります。

あなたのCSSは明らかに次のようなものになります:

.highlight {
    background:#ff00aa;
}

次にJavaScriptで:

element.className = element.className === 'highlight' ? '' : 'highlight';

2
それをどこに置くかは明らかです-変更したいHTMLの後のどこかに。
TeeJay 2014

1
これはほとんどの場合に有効ですが、色(または属性)が構成で定義されている場合、またはユーザーが入力した場合は、可能なすべての色のCSSクラスを作成できません;)
Juan Mendes

23
var element = document.getElementById('element');
element.style.background = '#FF00AA';


7

次のスクリプト要素をbody要素に追加します。

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>

6

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>


4

あなたはこれを試すことができます

var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";

例。

var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff

JSFIDDLE


1
element.style.background-colorは有効なJavaScriptではありません。これが、CSSプロパティがCamelCaseに変換される理由です。
CrazyIvan1974

4

あなたはJQueryでそれを行うことができます:

$(".class").css("background","yellow");

3

KISS回答:

document.getElementById('element').style.background = '#DD00DD';

クラスでそれをどのように行うことができますか?
Vignesh Subramanian 2015

クラスの場合document.getElementByClass('element').style.background = '#DD00DD';
MD Ashik

3

以下を使用できます。

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>



1

あなたは使うことができます

$('#elementID').css('background-color', '#C0C0C0');

これはjavascriptではなくjqueryです
Vignesh Subramanian 2015

@vignesh jQuery JavaScript です-__-
Novocaine

@Novocaine jQueryはJavaScriptを使用して作成されています。しかし、jQueryライブラリを含めない限り、$は機能しません;)
Vignesh Subramanian 2015

0

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

0

のCSSの変更 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>


複数のCSSの変更 HTMLElement

CSSスタイルを複数の要素に適用することを想像してください。たとえば、クラス名を持つすべての要素の背景色を作成しますbox lightgreen。次に、次のことができます。

  1. 要素を選択し、構造化.querySelectorAll解除構文Arrayを使用してオブジェクトに展開します

    const elements = [...document.querySelectorAll('.box')]
  2. で配列をループし、.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>


JavaScriptのCSSプロパティのリスト

完全なリストは次のとおりです。

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


-1
$(".class")[0].style.background = "blue";

この質問に対する正しい答えは十分にありますが、この答えは他の答えより優れたものはありません。
Novocaine、2015

ノボカインが言ったように、ここにはたくさんの答えがあります。ただし、今後は投稿を編集して、コードの機能と問題を解決する理由についての説明を追加することを検討してください。通常、コードが含まれているだけの回答(たとえそれが機能していても)は、通常、OPが問題を理解するのに役立ちません。
SuperBiasedMan 2015
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.