[英]How to styling nth-last-child(3) if last-child not have class disabled in css ? or javascript
[英]How do I use JavaScript and Nth-Last-Child to add and remove CSS classes?
无论如何,我都不是JavaScript向导,但是我试图找出一种使用JavaScript的方法,该方法可以基于一个按钮的单击向一系列DIV添加和删除类。 假设我有一个列表:
<div id="homepage">
<div class="hpFeature"></div>
<div class="hpFeature"></div>
<div class="hpFeature"></div>
<div class="hpFeature"></div>
<div class="hpFeature"></div>
</div>
<button class="featureButton">Click Here</button>
我的默认CSS用于渐进增强,因此至少有一张图片显示为后备:
.hpFeature:nth-child(1) {display:block;}
.hpFeature {display:none;}
.fide {position: absolute; left:-9999px;}
...到目前为止,我的JavaScript如下所示:
var count = $('.hpFeature').length;
$(document).ready(function () {
$('.hpFeature').css('display','block');
$('.hpFeature').addClass('fide');
$('.hpFeature:nth-child(' + count + ')').removeClass('fide');
});
$(function(){
$(".featureButton").click(function(){
$('.hpFeature').removeClass('fide');
});
});
因此,我正在尝试通过nth-last-child属性通过JavaScript显示第一个图像的方法,然后滚动浏览然后单击按钮时,它会转到计数中的下一个图像,这是一种简单的方法删除.fide,最后返回第一个(同样,我似乎无法让nth-last-child工作,但可以让nth-child工作)。
如果是我,我会将数组功能委托给本机javascript数组。
然后,我可以操纵该数组并将其读取为html。
所以我们可以创建一个数组
var hpFeatureArray = []
创建一个绑定到html的函数
function refreshArray() {
var content = ''
for (var i=0; i < hpFeatureArray.length; i++) content = content + '<div class="hpFeature"></div>'
$('#homepage').html(content)
}
刷新。
refreshArray()
就数据的实际操作而言,现在很容易使用本机JavaScript数组操作。
hpFeatureArray.push('whatever')
refreshArray()
我认为您可以仅使用“活动”类(以识别当前部分)来更改display
值,而不用在fide
中使用第nth-child
和极端位置。 像这样:
<div id="homepage">
<div class="hpFeature active"></div>
<div class="hpFeature"></div>
<div class="hpFeature"></div>
<div class="hpFeature"></div>
<div class="hpFeature"></div>
</div>
<button class="featureButton">Click Here</button>
。 。 。 并用以下代码替换CSS:
.hpFeature {display:none;}
.hpFeature.active {display:block;}
然后,您就是JS代码,只需执行以下操作:
$(document).ready(function() {
$(".featureButton").on("click", function() {
var $activeDiv = $(".active");
var $nextDiv = null;
if ($activeDiv[0] === $(".hpFeature:last-child")[0]) {
$nextDiv = $(".hpFeature:first-child");
}
else {
$nextDiv = $activeDiv.next();
}
$activeDiv.removeClass("active");
$nextDiv.addClass("active");
});
});
如果我了解您要正确执行的操作,那么应该可以找到想要的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.