1

我还在学习 JavaScript 的过程中。我想只使用 JavaScript 而不是 Jquery 来完成任务。

我有多个 div/图像,我正在尝试使用 z-index 进行操作,以及一个将图像随机化到前面的按钮。

我得到了随机图像数组,但正如你在 image[1] 中看到的那样……设置每个 changeZ 索引会很费力。所以我正在着手改变类的(如 image[0] 所示,所以我可以将 current 添加到新图像并在下一次将 current 发送到背景,然后删除 class 属性。我已经得到了元素单独工作,但无法将其放在一个数组中。

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);}; 
4

2 回答 2

0

首先,我相信您的问题可能出在 changeClassZIndex(i,tagName) 中,它可能看起来像这样:

if (document.getElementsByClassName == undefined) {
    document.getElementsByClassName = function(className)
    {
        var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
        var allElements = document.getElementsByTagName("*");
        var results = [];

        var element;
        for (var i = 0; (element = allElements[i]) != null; i++) {
            var elementClass = element.className;
            if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
                results.push(element);
        }

        return results;
    }
}

function changeClassZIndex(z,className) {
    var e = document.getElementsByClassName(className);
    for(var i = 0; i < e.length; i++) {
        e[i].style.zIndex = z;
    }
};

如果 getElementsByClassName 函数不存在,我将定义它,因为某些浏览器可能不支持它。

但是,我可能建议对您的问题采取不同的方法:

var images = new Array("scene1", "scene2", "scene3");

var currentPhoto = div.current
var whichImage = Math.floor(Math.random()*images.length);

// change all images to the background
for(var i = 0; i < images.length; i++)
{
    changeZIndex(-5, images[i]);
}
// change the one you want to the top
changeZIndex(5, images[whichImage]);

这样您就不必为每个图像编写函数,并且添加图像就像添加到数组一样简单。

于 2012-08-09T17:45:48.483 回答
0

这是因为 document.getElementsByTagName() 返回一个array元素,你不能对它做这样的操作。相反,您需要枚举它们并单独执行操作。

这是一个有效的 jsfiddle,它准确地显示了如何做到这一点:jsfiddle


作为旁注:如果有很多网络编程会教你一件事,那就是:

永远不要排除 jQuery 作为选项。

JQuery 是您最好的朋友,在这种情况下使用它可以将您的代码行数减少一半以上。

于 2012-08-09T17:59:11.590 回答