问题
I have checked everywhere looking for a solution to this, and have not been able to figure it out. The solution eludes me.
For complicated reasons, I can't simply change the margin/padding swap in CSS, so I'm trying to add style="z-index:5;"
in the first div, and then style="z-index:4;"
in the second div, etc. so that the last element on the page has the lowest z-index, and each element going toward the top adds one, so it always remains on top if there is any overlap, which is the case with some links that currently sit below the subsequent sibling element.
Stripped down sample code below: I know my counter is working, but the value of the incrementer (z) is not passing to the .css
method in the for loop. Any suggestions?
<style>
.subsection {
margin-top: -80px;
padding-top: 80px;
position: relative;
}
</style>
<script>
var set_zindex = function(){
var subsection = $('.subsection');
var subsections = subsection.length;
var z;
for ( z=subsections; z >=0; z-- ) {
subsection.css('z-index', z );
}
}
set_zindex();
</script>
<html>
<div class="subsection">some content</div> //add style="z-index:5:
<div class="subsection">some content</div> //add style="z-index:4:
<div class="subsection">some content</div> //add style="z-index:3:
<div class="subsection">some content</div> //add style="z-index:2:
<div class="subsection">some content</div> //add style="z-index:1:
</html>
回答1:
You are working with a jQuery collection (var subsection). You need to go over each item in that collection separately.
Something like:
subsection.each(function(i){
$(this).css('z-index', subsection.length-i);
});
回答2:
You should use z -= 1 in a for loop. Sometimes things get screwy otherwise. See here
And iterate with each.
subsection.each
(
function(i) {
$(this).css('z-index',subsections-i);
}
)
;
来源:https://stackoverflow.com/questions/13963740/incremental-countdown-to-change-z-index-value-of-sibling-elements