JavaScript permet d'accéder aux propriétés personnalisées CSS (également appelées variables CSS)
P粉420868294
P粉420868294 2023-10-20 22:42:04
0
2
610

Comment obtenir et définir des propriétés personnalisées CSS (propriétés accessibles via var(…) dans une feuille de style) à l'aide de JavaScript (plain ou jQuery) ?

C'est ma tentative infructueuse : cliquer sur le bouton modifie les propriétés font-weight 属性,但不会更改自定义 --mycolor habituelles :

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <style>
    body { 
      --mycolor: yellow;
      background-color: var(--mycolor);
    }
  </style>
</head>
<body>

  <p>Let's try to make this text bold and the background red.</p>
  <button onclick="plain_js()">Plain JS</button>
  <button onclick="jQuery_()">jQuery</button>

  <script>
  function plain_js() { 
    document.body.style['font-weight'] = 'bold';
    document.body.style['--mycolor'] = 'red';
  };
  function jQuery_() {
    $('body').css('font-weight', 'bold');
    $('body').css('--mycolor', 'red');
  }
  </script>
</body>
</html>

P粉420868294
P粉420868294

répondre à tous(2)
P粉421119778

Solution native

La méthode standard pour obtenir/définir des variables CSS3 est .setProperty().getPropertyValue().

Si vos variables sont des variables globales (déclarées dans :root), vous pouvez utiliser ce qui suit pour obtenir et définir leurs valeurs.

// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');

Cependant, si la valeur de var a été définie à l'aide de .setProperty(), le getter ne renverra que cette valeur. S'il est défini via une déclaration CSS, undefined sera renvoyé. Découvrez-le dans cet exemple :

let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
  <div>Red background set by --myVariable</div>

Pour éviter ce comportement inattendu, vous devez appeler la méthode .getPropertyValue() 之前使用 getCompulatedStyle(). Le getter ressemblera alors à ceci :

getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');

À mon avis, l'accès aux variables CSS devrait être plus simple, plus rapide, intuitif et naturel...


Mon approche personnelle

J'ai implémenté CSSGlobalVariables un petit assistant javascript ( pour un accès et une manipulation plus faciles .

// get the document CSS global vars
let cssVar = new CSSGlobalVariables();
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );

Toutes les modifications appliquées aux propriétés de l'objet sont automatiquement converties en variables CSS.

Disponible : https://github.com/colxi/ css-global variables

P粉863295057

Vous pouvez utiliser document.body.style.setProperty('--name', value); :

var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get

document.body.style.setProperty('--foo-bar', newValue);//set
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!