我仍在学习 JavaScript 过程中。我想仅使用 JavaScript 而无需使用 Jquery 来完成该任务。
我有多个 div/图像,我正在尝试使用 z-index 进行操作,以及一个将图像随机化到前面的按钮。
我让随机图像数组可以工作,但是正如您在图像[1]中看到的那样......设置每个changeZ索引将很费力。因此,我开始更改类的(如 image[0] 中所示),以便我可以将当前图像添加到新图像,并在下一次循环时将当前图像发送到背景,然后删除类属性。我已将元素添加到单独工作,但很难将其放在一个数组中。
function changeZIndex(i,id) {
document.getElementById(id).style.zIndex=i;};
function changeClassZIndex(i,tagName){
document.getElementsByTagName("*").style.zIndex=i;};
function getImage(){
var whichImage=Math.floor(Math.random()*3);
var image=new Array()
var currentPhoto = div.current
image[0]=function() {
changeZIndex(5,"scene1");
changeClassZIndex(-5,"current");
currentPhoto.removeClass('current')
document.getElementById("scene1").className += "current"; };
image[1]=function() {
changeZIndex(5,"scene2");
changeZIndex(-5,"scene1");
changeZIndex(-5,"scene3");
changeZIndex(-5,"scene");
};
image[2]=function() {
changeZIndex(5,"scene3");
changeZIndex(-5,"scene");
changeZIndex(-5,"scene2");
changeZIndex(-5,"scene1");
};
image[whichImage].apply(undefined);};
最佳答案
这是因为 document.getElementsByTagName() 返回一个元素的数组
,您无法对其执行类似的操作。相反,您需要枚举它们并单独执行操作。
这是一个有效的 jsfiddle,它准确地展示了如何做到这一点: jsfiddle
<小时/>顺便说一句:如果说很多网络编程会教你一件事,那就是:
永远不要、永远排除 jQuery 作为一种选择。
JQuery 是您最好的 friend ,在这种情况下使用它可以将您的代码行数减少一半以上。
关于javascript - 使用 z-index 更改类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11888658/