javascript opacity(透明度)を変更する

javascript opacity(透明度)を変更する

javascriptで、opacity(透明度)を変更するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 102.0.5005.115

opacity(透明度)変更

style.opacityに数値を指定すれば、opacity(透明度)を変更することが可能です。

<button class="btn" onclick="hoge()">buuton</button>

<script>

function hoge(){
  let obj = document.getElementsByClassName("btn")[0];
  obj.style.opacity = 0.5; // 透明度を50%に指定
}

</script>

実行結果

透明度は 0%(0) ~ 50%(0.5) ~ 100%(1)で指定できます。
※マイナスを指定すると「0」と同じ結果になります。

サンプルコード

以下は、
「 透過 」ボタンをクリックすると、フォームに入力した値でボタンを透過する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- Font Awesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 25px;
    width: 800px;
  }
</style>
<script>

  function hoge() {

    // フォームの値を取得
    let num = document.getElementById('num').value;

    // 透明度変更
    let obj = document.getElementsByClassName("btn")[0];
    obj.style.opacity = num;

  }

</script>

<body>
  <div class="main">

    <button type="button" class="btn btn-danger bmd-btn-fab">
      <i class="fas fa-atlas"></i>
    </button>

    <form>
      <div class="form-group">        
        <input id="num" type="text" class="form-control mt-1">
      </div>
    </form>

    <button onclick="hoge()" class="btn btn-raised btn-primary mt-1" type="button">
      透過
    </button>

  </div>
</body>

</html>

透過されていることが確認できます。