因此,目前在課堂上,我們試圖僅使用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上述方式而不是
你可以提供一個樣本小提琴說明問題了嗎? –
我很想......但你知道,學術工作。 – SomeStudent
如果'a15'是類名稱,請使用document.getElementsByClassName('a15')[0]而不是getElementById。 Top和Left屬性僅適用於CSS「position:absolute;」 https://jsfiddle.net/unj1njt7/ –