私は要素の位置は、別の位置とピクセルの位置として表現できますか?
document.getElementById('first').style.top = document.getElementById('second')
.style.top + 80;
を試してみましたが、それは動作するようには思えません。これはどのように達成できますか?
私は要素の位置は、別の位置とピクセルの位置として表現できますか?
document.getElementById('first').style.top = document.getElementById('second')
.style.top + 80;
を試してみましたが、それは動作するようには思えません。これはどのように達成できますか?
はい、位置を解析して、新しい値とユニットパーツストリングを使用して文字列を再構築することで実行できます。
var match = document.getElementById('second').style.top.match(^(\d+(?:\.\d+)?)(.*)$);
document.getElementById('first').style.top = (parseFloat(match[1]) + 80) + match[2];
ニーナ・ショルツの答えは、これを行うには本当に素晴らしい方法です。多くの場合、野生では2つの方法があります。どちらのoffsetTop
とoffsetLeft
ゲットコンピュースタイル例
let div1 = document.getElementById('one');
let div2 = document.getElementById('two');
// we use getComputedStyle to get the top and left of div1
// we use slice to remove 'px' from the property value.
div1Top = getComputedStyle(div1).getPropertyValue('top').slice(0,-2);
div1Left = getComputedStyle(div1).getPropertyValue('left').slice(0,-2);
//we can now manipulate the value any way we please
//and set the values to the second div.
div2.style.top = (div1Top + 30) + 'px';
div2.style.left = div1Left + 'px';
上部オフセットと左の例
を使用することによって、最も一般的getComputedStyle
とそのgetPropertyValue
方法、またはを使用して、 Offset Example
let div1 = document.getElementById('one');
let div2 = document.getElementById('two');
div2.style.top = (div1.offsetTop + 30) + 'px';
div2.style.left = div1.offsetLeft + 'px';
オフセットは、わかりやすく、より簡潔でありながら読みやすくなっているため、より一般的に使用されます。
位置の値は、 '%'、 'px'、' em'、 'rem'などで割り当てることができます。常に' px'で作業している場合は問題ありません。 :) https://developer.mozilla.org/en-US/docs/Web/CSS/top – tiomno
@timo、ダイナミックユニットを使用しています。 –
ニースのコードスニペットニーナ、もし私ができれば別の親指をあげよう。 – tiomno