0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript で CSS を動的に変更できないとき

Posted at

JavaScript で css を操作して画像の幅を変えようとしても、反映されない。

javascript50px.png

50pxのアイコン

javascript150px.png

JavaScriptで150pxにしたい

結論

"px" をつけます。↓例

const img = document.getElementById("img1");
const width = 150;
img.style.width = width + "px";

JavaScriptでCSSの値を書き換える方法

JavaScript で css の要素を操作するときは「文字列」を代入しなければならないようです。

例えば下のコードはうまく動きません。

const img = document.getElementById("img1");
const width = 150;
img.style.width = width;   //画像が150pxにならない

javascript50px.png

画像は50pxのまま

width は数値なので、img.style.widthにそのまま代入しても期待した結果にはなりません。そこで、

img.style.width = width + "px";   //150px

のように "px" をつけることで、文字列に変換します。

javascript150px.png

150pxに設定できた

CSSの値をJavaScriptで取得する場合

逆に、css の値を javascript で使う場合、

const width = img.style.width;   //"50px"

のように書くと width は例えば "50px" という文字列になってしまいます。

数値として使いたい場合は parseInt 関数を使いましょう。

const width = pareseInt(img.style.width);   //50

これで width に 50 という数値が入ります。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?