كيفية تعيين لون خلفية CSS لـ HTML باستخدام JavaScript
-
08-06-2019 - |
سؤال
كيف يمكنني ضبط لون خلفية CSS لعنصر HTML باستخدام JavaScript؟
المحلول
بشكل عام، يتم تحويل خصائص CSS إلى JavaScript عن طريق جعلها CamelCase بدون أي شرطات.لذا background-color
يصبح backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
نصائح أخرى
قد تجد أن الكود الخاص بك أكثر قابلية للصيانة إذا احتفظت بجميع أنماطك، وما إلى ذلك.في CSS وقم فقط بتعيين/إلغاء تعيين أسماء الفئات في JavaScript.
من الواضح أن CSS الخاص بك سيكون شيئًا مثل:
.highlight {
background:#ff00aa;
}
ثم في جافا سكريبت:
element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';
أو باستخدام القليل من jQuery:
$('#fieldID').css('background-color', '#FF6600');
أضف عنصر البرنامج النصي هذا إلى عنصر جسمك:
<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 يمكننا استهداف فئة العنصر أو معرفه لتطبيق خلفية CSS أو أي أنماط أخرى
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
هناك العديد من الطرق وأعتقد أنها سهلة وبسيطة للغاية
يمكنك استخدام
$('#elementID').css('background-color', '#C0C0C0');
جافا سكريبت:
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
تغيير CSS لـ أ HTMLElement
يمكنك تغيير معظم خصائص CSS باستخدام JavaScript، استخدم هذا البيان:
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
.إذا تستطيع:
حدد العناصر مع
.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
$(".class")[0].style.background = "blue";