Onclick将元素设置为relative,否则将其他div设置为absolute

时间:2018-01-23 10:08:15

标签: javascript jquery

我正在尝试将元素设置为相对onclick。我的代码将div设置为relative,但是我需要将其他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");  
});

2 个答案:

答案 0 :(得分:5)

您不需要为每个元素拥有多个事件。您可以使用clicked元素的索引从.case-study set:

进行过滤
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"); 

答案 1 :(得分:0)

Vanilla JS:

let section = YourSection
section.onclick = event=>{
    if (event.target.nodeName.tolowerCase() !== yourChildNodesName) return false
    Array.from(event.target.parentNode.children).forEach(node=>{
        node.style.position = node === event.target ? 'relative' : 'absolute'
    })
}