2017-08-14 72 views
-1

如何让“1”变为变量/动态。 当我点击第二个按钮, “1” 将变为 “2”前后变量n-child(n)

#button li:nth-child(1) a { 
background-color: #5cb85c; 
} 
#button li:nth-child(1) a:before { 
border-color: #5cb85c; 
border-left-color: transparent; 
} 
#button li:nth-child(1) a:after { 
border-left-color: #5cb85c; 
} 

第一个CSS类是使用

$("#button li:nth-child(2) a").css("background-color", "#5cb85c"); 

工作时:前:没有了。

或其他任何解决方案都可以。 当我点击第二个按钮时,将应用相同的CSS集。并在第三个按钮。等等。

谢谢!很多来自乔治的解决方案的尝试后,终于

解决方案从@giorgio

,这里是基于我的示例CSS它是如何工作的。

.button-select a { 
background-color: #5cb85c !important; 
} 
.button-select a:before { 
border-color: #5cb85c !important; 
border-left-color: transparent !important; 
} 
.button-select a:after { 
border-left-color: #5cb85c !important; 
} 

我需要添加!important重写默认样式。 然后在我的onClick,

$('#buttons li').eq(n).toggleClass('button-select'); 

n<li><ul id = "buttons">

+1

而不是改变'background-color'添加一个类(例如'active')。然后你可以用'$(“.active”)选择下一个元素。next()' – Andreas

+1

谢谢@caramba纠正 – dens

+0

我会尝试你的建议@Andreas谢谢! – dens

回答

0

最简单的解决方案索引不使用:nth-child()但设置一些课程,并应用在其上的::before:/::after选择。例如;

.background-red::before { background: red; } 
.background-blue::before { background: blue; } 

现在用jQuery/javascript查找要更改的元素并切换类。例如;

$('.my-selector').eq(n).toggleClass('background-red'); 

不断变化的伪选择是它们不是DOM的一部分的问题;你将无法直接修改它们。

+0

这是正确的吗?对不起,我是新来的CSS。 $('#button')。eq(2).toggleClass('button-select'); #button-select:before { \t border-color:#5cb85c; \t border-left-color:transparent; } – dens

+0

好吧,因为它是一个类,你的CSS应该是'.button-select {...}'而不是'#button-select {...}',这是一个id的选择器 – giorgio