2016-12-24 8 views

答えて

6

はい、位置を解析して、新しい値とユニットパーツストリングを使用して文字列を再構築することで実行できます。

var match = document.getElementById('second').style.top.match(^(\d+(?:\.\d+)?)(.*)$); 

document.getElementById('first').style.top = (parseFloat(match[1]) + 80) + match[2]; 
+0

位置の値は、 '%'、 'px'、' em'、 'rem'などで割り当てることができます。常に' px'で作業している場合は問題ありません。 :) https://developer.mozilla.org/en-US/docs/Web/CSS/top – tiomno

+1

@timo、ダイナミックユニットを使用しています。 –

+0

ニースのコードスニペットニーナ、もし私ができれば別の親指をあげよう。 – tiomno

1

ニーナ・ショルツの答えは、これを行うには本当に素晴らしい方法です。多くの場合、野生では2つの方法があります。どちらのoffsetTopoffsetLeft

ゲットコンピュースタイル例

Computed Style Example

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'; 

オフセットは、わかりやすく、より簡潔でありながら読みやすくなっているため、より一般的に使用されます。

関連する問題