2017-06-04 9 views
0

我试图创建一个轮盘,其中所有三个项目都是可见的,并且它们在点击导航时切换位置(在只在左箭头上工作的时刻)。使用JS来更改三个div ID(carousel-esque),工作两次,但然后跳过一个div

我这样做是通过将每个div分配给一个使用id的位置,并使用JS来更改ID。

它按照预期工作,但是当#pos3(香蕉)变成#pos1时,它由于某种原因被跳过,#pos2和#pos3只是交换位置。

的CSS:

#pos1{ 
left:10%; 
} 

#pos2{ 
left:30%; 
z-index:2; 
top:50px; 
background:rgba(255,255,255,0.9); 
} 

#pos3{ 
left:60%; 
} 

的JS

document.getElementById("left").onclick = function(){ 
    document.getElementById("pos2").setAttribute("id", "pos1"); 
    document.getElementById("pos3").setAttribute("id", "pos2"); 
    document.getElementById("pos1").setAttribute("id", "pos3");  
}; 

Fiddle here

回答

0

document.getElementById(“pos2”)。setAttribute(“id”,“pos1”); document.getElementById(“pos3”)。setAttribute(“id”,“pos2”);
document.getElementById(“pos1”)。setAttribute(“id”,“pos3”);

在第三行执行时,pos1不存在,因为您已经在第一行更改了该位置。

只需引入一个临时ID来解决这个问题。

document.getElementById(“pos1”)。setAttribute(“id”,“temp”); document.getElementById(“pos2”)。setAttribute(“id”,“pos1”); document.getElementById(“pos3”)。setAttribute(“id”,“pos2”);
document.getElementById(“temp”)。setAttribute(“id”,“pos3”);

+0

谢谢!只是想到了上述情况,但无论如何给你绿色检查 – noob

0

没有测试它自己,它看起来当你改变#pos2#pos1一样,你最终带有id为0123的2个元素,因为原始#pos1尚未更改为#pos3。所以,当代码到达#pos1#pos3的时候,它会更改这两个元素,从而使您没有#pos1

+0

啊我知道这是类似的东西,只是没有完全到达那里。谢谢!有没有办法同时改变两者?我是否以错误的方式处理这个问题? – noob

+0

可能。我个人不喜欢改变ID。赛门铁克一个ID应该确定一个单一的元素,所以真的不应该改变。你最好使用我认为的类,也许可以用某种方式保存ID来管理每个元素的位置。 –

+1

想出来 - 添加一个#pos4“持有位置”,它与#pos1相同,然后在函数结束时切换它们使其循环。动画不太正确,但可以修复 - 目前我已经完成了我设定要做的事情。谢谢! – noob

相关问题