javascript 指定した要素のstyleをコピーして使用する
- 作成日 2022.10.22
- javascript
- javascript
javascriptで、指定した要素のstyleをコピーして使用するサンプルコードを記述してます。「getComputedStyle」を使用すればスタイルに関する情報を取得できるので、これを利用します。実際に、実行した結果を動画で掲載しております。
環境
- OS windows11 pro 64bit
- ブラウザ chrome 106.0.5249.103
指定した要素のstyleをコピーして使用
指定した要素のstyleをコピーして使用するには、「getComputedStyle」でスタイル情報を取得して対象の要素に適応します。
<style>
#one {
background-color: #37B507;
width: 100px;
height: 100px
}
</style>
<div id="one" style="">
copy元
</div>
<div id="two">copy先</div>
<button id="btn">button</button>
<script>
document.getElementById('btn').addEventListener('click',function(){
const one = document.getElementById('one');
const two = document.getElementById('two');
const oneStyles = getComputedStyle(one);
two.style.backgroundColor = oneStyles.backgroundColor;
two.style.width = oneStyles.width;
two.style.height = oneStyles.height;
}
)
</script>
実行結果
コードを簡潔化
また、javascript部はdocument.getElementByIdを省略して「id名」のみで記述することも可能です。関数もアロー関数を使用できます。
btn.addEventListener('click',() => {
const oneStyles = getComputedStyle(one);
two.style.backgroundColor = oneStyles.backgroundColor;
two.style.width = oneStyles.width;
two.style.height = oneStyles.height;
}
)
サンプルコード
以下は、
「 実行 」ボタンをクリックすると、「copy元」のstyleをコピーして適応するサンプルコードとなります。
※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-75 mx-auto" style="margin-top:200px">
<h2><span class="badge badge-primary">copy元</span></h2>
<h2><span id="foo">結果</span></h2>
<button type="button" onclick="hoge()" class="btn btn-raised btn-primary">
実行
</button>
</div>
<script>
const hoge = () => {
const styles = getComputedStyle(document.getElementsByClassName("badge")[0]);
foo.style.backgroundColor = styles.backgroundColor;
foo.style.width = styles.width;
foo.style.height = styles.height;
foo.style.color = styles.color;
foo.style.borderRadius = styles.borderRadius;
foo.style.padding = styles.padding;
foo.style.fontSize = styles.fontSize;
foo.style.fontWeight = styles.fontWeight;
foo.style.display = styles.display;
}
</script>
</body>
</html>
コピーされていることが確認できます。
-
前の記事
Android Studio 単語単位で削除するショートカットキー 2022.10.22
-
次の記事
javascript 文字列内で最初に見つかった数値を取得する 2022.10.23
コメントを書く