LoginSignup
9
6

More than 5 years have passed since last update.

javascript初心者がobjectを移動させる際にハマったこと

Posted at

ハマったこと

  1. オブジェクトの取得の仕方
  2. 位置をもつプロパティがどれか
  3. 代入しているはずなのに変わらない

1. オブジェクトの取得の仕方

//IDで取得
var object = document.body.getElementById("hoge");

詳しくはこちらに色々書いてあったのでおいおい読みたい
https://qiita.com/amamamaou/items/25e8b4e1b41c8d3211f4

2. 位置をもつプロパティがどれか

位置を持つプロパティはobject.style.topなど
多分styleはcssのこと

//位置を取得
console.log(object.style.top);

3. 代入しているはずなのに変わらない

これでどのプロパティをいじればいいかがわかったのでここに普通に代入して見ようと次のようなコードを書いたところ動かない。

//10の位置に動けや
object.style.top = 10;

どうやらobjectのcssでいうpositionがabsoluteになっていないと動かないのでjsで指定してあげる

//位置を親からの絶対位置に指定
object.style.position = "absolute";
//10の位置に動けや
object.style.top = 10;

しかし動かない。調べてみると訳のわからん事実が判明した。
どうやら後ろに + "px"とつけると動くらしい

//位置を親からの絶対位置に指定
object.style.position = "absolute";
//10の位置に動くぜ
object.style.top = 10 + "px";

おそらくだがjavascript上でobjectのstyle(css)を指定するときは全てstringで指定しなくてはなのでは。
ここでつまづいたので同じ思いをした人は助かってください。

9
6
2

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
9
6