تغيير متغيرات CSS باستخدام JavaScript
تغيير المتغيرات باستخدام JavaScript
تتمتع متغيرات CSS بإمكانية الوصول إلى DOM ، مما يعني أنه يمكنك تغييرها باستخدام JavaScript.
فيما يلي مثال لكيفية إنشاء برنامج نصي لعرض المتغير --blue وتغييره من المثال المستخدم في الصفحات السابقة. في الوقت الحالي ، لا تقلق إذا لم تكن معتادًا على JavaScript. يمكنك معرفة المزيد حول JavaScript في برنامج JavaScript التعليمي الخاص بنا :
مثال
<script>
// Get the root element
var r = document.querySelector(':root');
// Create a function for getting a variable value
function
myFunction_get() {
// Get the styles (properties and values) for the
root
var rs = getComputedStyle(r);
// Alert the value of
the --blue variable
alert("The value of --blue is: " +
rs.getPropertyValue('--blue'));
}
// Create a function for setting a
variable value
function myFunction_set() {
// Set the value of
variable --blue to another value (in this case "lightblue")
r.style.setProperty('--blue', 'lightblue');
}
</script>
دعم المتصفح
تحدد الأرقام الواردة في الجدول إصدار المتصفح الأول الذي يدعم
var()
الوظيفة بشكل كامل.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
وظيفة CSS var ()
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |