2017-02-19 25 views
0

所以我有一個div,我想改變它的類的位置,這是我的代碼。如何改變一個類的位置

<h1 class="test">Hi!</h1> 

<script> 
x = document.getElementsByClassName('test') 

x[0].style.top = 500; 

</script> 

但是這個位置仍然是一樣的,爲什麼?

回答

1

首先,默認元件positionstatic,這意味着任何操縱到toprightbottomleftCSS性能是不會可視地施加。

所以,如果你想改變top特性,還需要使用以下任意值的更改的元素position

relative absolute fixed

您可以瞭解更多有關CSS位置Developer Mozilla

所以爲了讓你的情況下工作,下面的代碼爲如下:

<h1 class="test">Hi!</h1> 

<script> 
    x = document.getElementsByClassName('test') 

    x[0].style.position = 'relative'; // Changed the position property to relative. 
    x[0].style.top = '500px'; // Must be wrapped in quotes, and append the measurement unit in the value in this case the 'px'. 

</script> 

您還可以瞭解更多有關CSS度量單位here