Javascript 如何使用动态添加的类名移动div
因此,目前在课堂上,我们正试图只用Javascript、CSS和基本HTML制作15个拼图。我也不允许修改html,有趣的东西。无论如何,我能够将动态类名添加到html中,并在css中引用它们,如下所示:Javascript 如何使用动态添加的类名移动div,javascript,html,css,Javascript,Html,Css,因此,目前在课堂上,我们正试图只用Javascript、CSS和基本HTML制作15个拼图。我也不允许修改html,有趣的东西。无论如何,我能够将动态类名添加到html中,并在css中引用它们,如下所示: var children = document.getElementById("puzzlearea").childNodes; //iterates through all children for (child in children) { //if child
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;
}
}
document.getElementsByTagName('div')[15].onclick = function () {
alert("work"); //does actually only happen on correct div
this.style.top = "500px" //still doesn't move it
}
在我们的CSS中,我们可以通过简单地声明.a15并为其指定所需的边距、大小、图像位置等来引用它。但是,当我尝试使用document.getElementById.a15.style.top=200px或仅使用a15引用其id来移动它时,它不起作用。上面提到的方法是我在stack上看到的移动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;
}
}
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引用它。您正在向这些div添加类,因此当您引用它们时,而不是:
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 ...
工作示例以防万一:您能提供一个小提琴示例来说明您的问题吗?我很乐意……但您知道,学术工作。如果“a15”是类名,请使用document.getElementsByClassName“a15”[0]而不是getElementById。顶部和左侧属性仅适用于CSS位置:绝对;我明白了,使用上面的代码片段,它也会随着相对移动,不过很有趣。看,我是这么想的,但这不起作用。这两种选择都不管用唉,在一个一切都有意义的世界里,应该是可行的,可悲的是,这不是一个这样的世界。这是最令人困惑的,因为我们可以像普通类一样在CSS中清晰地引用它。