簡體   English   中英

如何在 JavaScript 中使用 css 屬性設置 HTML 元素的背景顏色

[英]How to set background color of HTML element using css properties in JavaScript

如何在 JavaScript 中使用 css 設置 HTML 元素的背景顏色?

通常,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';
var element = document.getElementById('element');
element.style.background = '#FF00AA';

或者,使用一點 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

JSFIDDLE

吻 答案:

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

你可以用 JQuery 做到這一點:

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

您可以使用:

<script type="text/javascript">
  Window.body.style.backgroundColor = "#5a5a5a";
</script>
$("body").css("background","green"); //jQuery

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

有很多方法我認為這很容易和簡單

Plunker 上的演示

$('#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

查詢:

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

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

更改HTMLElement CSS

您可以使用 JavaScript 更改大多數 CSS 屬性,請使用以下語句:

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

其中<selector><property><new style>都是String對象。

通常,樣式屬性的名稱與 CSS 中使用的實際名稱相同。 但只要有更多的詞,就會是駝峰式:例如background-colorbackgroundColor改變。

以下語句將#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

想象一下,您想將 CSS 樣式應用於多個元素,例如,將所有類名box lightgreen元素的背景顏色設置為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

一個簡單的js可以解決這個問題:

document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM