我正在尝试将元素设置为相对onclick。我拥有的代码可以将div设置为相对,但我需要将其他div重置为绝对位置。到目前为止,我有...
<div class="case-studies">
<section class="pagination">
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>
</section>
<div class="case-study" style="background:blue;"></div>
<div class="case-study" style="background:green;"></div>
<div class="case-study" style="background:orange;"></div>
<div class="case-study" style="background:pink;"></div>
</div>
$('.pagination div:first-of-type').on('click', function() {
$('.case-study:first-of-type').css("position", "relative");
});
$('.pagination div:nth-of-type(2)').on('click', function() {
$('.case-study:nth-of-type(2)').css("position", "relative");
});
$('.pagination div:nth-of-type(3)').on('click', function() {
$('.case-study:nth-of-type(3)').css("position", "relative");
});
$('.pagination div:last-of-type').on('click', function() {
$('.case-study:last-of-type').css("position", "relative");
});
最佳答案
您不需要为每个元素具有多个事件。您可以使用点击元素的索引从.case-study
集合中进行过滤:
var $caseStudies = $('.case-study');
$('.pagination div').on('click', function() {
$caseStudies.css("position", "absolute");
$caseStudies.eq($(this).index()).css("position", "relative");
});
您还可以将代码范围缩小到:
$caseStudies.css("position", "absolute").eq($(this).index()).css("position", "relative");
关于javascript - Onclick将元素设置为相对,否则将其他div设置为绝对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48399025/