▲TOPへ戻る

【javascript】CSSを追加、削除、変更する方法

topBtn

width: 300px;

height: 150px;

HTMLとCSSは以下の通りです。最低限の記述です。

HTML
  <div class="content">
    <div class="box"></div>
  </div> 
CSS
  .box {
    width: 300px;
    height: 150px;
    background: red;
    color: #fff;
  } 

追加・変更

要素.style.プロパティ名 = 値(value);

javascript
  const box = document.querySelectorAll(".box");
  box.style.width = '90%';
  box.style.height = '100px';
  box.style.background = 'bule';

プロパティ名を記述する時の注意

ハイフン(-)があるプロパティを記述する時は注意してください。 backgroundImageのようにキャメルケースで記述してください。

javascript
  box.style.backgroundColor = ''; /*background-color*/
  box.style.backgroundImage = ''; /*background-image*/
  box.style.fontSize = '';  /*font-size*/
  box.style.fontWeight = '';  /*font-weight*/

cssText まとめて記述

要素.style.cssText = 'CSSを記述'

javascript
  const box = document.querySelectorAll(".box"); 
  box.style.cssText = 'width: 90%; height: 100px; background: bule;';

削除

要素.style.プロパティ名 = '(空)'

javascript
  box.style.width = '';
  box.style.height = '';
  box.style.background = '';
  box.style.cssText = '';

応用

width: 300px;

height: 150px;

javascript
  const box = document.querySelector(".box");
  const changeCss = document.querySelector(".changeCss");   //  ボタンを取得

  changeCss.addEventListener("click", ()=>{
    if(changeCss.textContent == '追加'){
      box.style.width = '90%';
      box.style.height = '100px';
      box.style.background = 'blue';
      changeCss.textContent = '元に戻す';
    } else {
      box.style.width = '';
      box.style.height = '';
      box.style.background = '';
      changeCss.textContent = '追加';
    }
  })  
point

追加・変更 : 要素.style.プロパティ名 = 値(value);

まとめて記述:要素.style.cssText = 'CSSを記述';

削除 : 要素.style.プロパティ名 = '(空)';

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ