16 ответов:
В общем, свойства CSS преобразуются в JavaScript, делая их camelCase без каких-либо тире. Так что
background-colorстановитсяbackgroundColor.function setColor(element, color) { element.style.backgroundColor = color; }
вы можете обнаружить, что ваш код более удобен для обслуживания, если вы сохраняете все свои стили и т. д. в CSS и просто установить / отменить имена классов в JavaScript.
ваш CSS, очевидно, будет что-то вроде:
.highlight { background:#ff00aa; }затем в JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
добавьте этот элемент скрипта в элемент вашего тела:
<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
вы можете использовать:
<script type="text/javascript"> Window.body.style.backgroundColor = "#5a5a5a"; </script>
$('#ID / .Class').css('background-color', '#FF6600');С помощью jquery мы можем настроить класс или идентификатор элемента для применения фона css или любых других стилей
$("body").css("background","green"); //jQuery document.body.style.backgroundColor = "green"; //javascriptтак много способов есть, я думаю, что это очень легко и просто
изменение CSS a
HTMLElementвы можете изменить большинство свойств CSS с помощью JavaScript, используйте этот оператор:
document.querySelector(<selector>).style[<property>] = <new style>здесь
<selector>,<property>,<new style>всеStringобъекты.обычно свойство style будет иметь то же имя, что и фактическое имя, используемое в 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 к более чем одному элементу, например, сделать цвет фона всех элементов с именем класса
boxlightgreen. Тогда вы может:
выберите элементы с
.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>
список свойств CSS в JavaScript
вот полный список:
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
Javascript:
document.getElementById("ID").style.background = "colorName"; //JS ID document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS ClassJquery:
$('#ID/.className').css("background","colorName") // One style $('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
Comments