質問

JavaScript を使用して HTML 要素の CSS 背景色を設定するにはどうすればよいですか?

役に立ちましたか?

解決

一般に、CSS プロパティはダッシュなしのキャメルケースにすることで JavaScript に変換されます。それで background-color になる backgroundColor.

function setColor(element, color)
{
    element.style.backgroundColor = color;
}

他のヒント

すべてのスタイルなどを保持すると、コードがより保守しやすくなる場合があります。CSS で、JavaScript でクラス名を設定/設定解除するだけです。

CSS は明らかに次のようなものになります。

.highlight {
    background:#ff00aa;
}

次に、JavaScript で次のようにします。

element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';

または、ちょっとした jQuery を使用します。

$('#fieldID').css('background-color', '#FF6600');

この script 要素を 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

ジェスフィドル

JQuery を使用してそれを行うことができます。

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

キスの答え:

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

次のものが使用できます。

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>
$('#ID / .Class').css('background-color', '#FF6600');

jquery を使用すると、要素のクラスまたは ID をターゲットにして CSS 背景やその他のスタイルを適用できます。

$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

方法はたくさんありますが、とても簡単でシンプルだと思います

プランカーのデモ

使用できます

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

JavaScript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class

Jクエリ:

$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style

のCSSを変更する HTMLElement

JavaScript を使用してほとんどの CSS プロパティを変更できます。次のステートメントを使用します。

document.querySelector(<selector>).style[<property>] = <new style>

どこ <selector>, <property>, <new style> 全てです String オブジェクト。

通常、スタイル プロパティは、CSS で使用される実際の名前と同じ名前になります。ただし、複数の単語がある場合は常にキャメルケースになります。例えば 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
$(".class")[0].style.background = "blue";
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top