2016-09-17 132 views
-1

因此,目前在課堂上,我們試圖僅使用Javascript,CSS和基本HTML製作15-益智。我也不允許修改html,有趣的東西。反正我是能夠動態類名稱添加到我的HTML和CSS中引用它們如下:如何使用動態添加的類名稱移動div

var children = document.getElementById("puzzlearea").childNodes; 

//iterates through all children 
    for (child in children) { 

     //if children is a div then we do something to it 
     if (children[child].nodeName == "DIV") { 
      //add a class that corresponds to a css to the current div child that we are on 
      children[child].classList.add('a' + i); 
      i = i + 1; 
     } 
    } 

在我們的CSS那麼我們可以通過簡單地陳述.a15和分配它所需的保證金來引用它,大小,圖片定位等等。但是,當我嘗試通過使用document.getElementById(「.a15」)。style.top =「200px」 - 或僅僅是「a15」引用其ID時,它不起作用。上面提到的方式是我爲了移動div而在棧中看到的建議。

目前我想的東西如下:

document.getElementsByTagName('div')[15].onclick = function() { 
      alert("work"); //does actually only happen on correct div 
      this.style.top = "500px" //still doesn't move it 
    } 

然而,這個它仍然不動它,當然,獲取所有的div。因此,問題仍然是:「如何使用動態添加的類名稱移動div?」

編輯:通過提及位置應該在CSS中相對移動,但我仍然只能參考它通過直接的iD上述方式而不是

+0

你可以提供一個樣本小提琴說明問題了嗎? –

+0

我很想......但你知道,學術工作。 – SomeStudent

+1

如果'a15'是類名稱,請使用document.getElementsByClassName('a15')[0]而不是getElementById。 Top和Left屬性僅適用於CSS「position:absolute;」 https://jsfiddle.net/unj1njt7/ –

回答

3

你加入class那些DIV(S),所以當你不是引用它們:

document.getElementById(".a15").style.top ... 

它應該是:

document.getElementsByClassName("a15").style.top ... // without . 

請注意,getElementsByClassName返回具有該特定類的元素數組。所以,你可能需要做一些像

var currentDiv = document.getElementsByClassName("a15")[0] // assuming you have only one div with class a15 
// then 
currentDiv.style.top ... 

工作示例以防萬一:https://jsfiddle.net/Laf54y1a/3/

+0

看到了,這就是我的想法,但這不起作用。這兩個選項都沒有工作 – SomeStudent

+0

更新了答案,看看是否有幫助。 – leninhasda

+0

唉,在一個事情有意義的世界裏應該有效,可悲的是這不是這樣一個世界。這是最令人困惑的,因爲我們可以像普通的類一樣在CSS中清楚地引用它。 – SomeStudent