幻灯片显示增加z-index并降低不透明度

时间:2012-04-17 17:27:24

标签: javascript jquery css z-index opacity

第一次发帖,请耐心等待。

我正在尝试创建幻灯片:

  • 为每个<section>
  • 分配一个z-index
  • 将所有幻灯片设置为不透明度为0.7
  • 为当前顶部幻灯片指定不透明度为1

这是HTML:

<div id="slides">
  <section class="slide">
    <article>
      <h1>6</h1>
    </article>
  </section>
  <section class="slide">
    <article>
      <h1>5</h1>
    </article>
  </section>
  <section class="slide">
    <article>
      <h1>4</h1>
    </article>
  </section>
  <section class="slide">
    <article>
      <h1>3</h1>
    </article>
  </section>
  <section class="slide">
    <article>
      <h1>2</h1>
    </article>
  </section>
  <section class="slide">
    <article>
      <h1>1</h1>
    </article>
  </section>
</div>
<div id="prev">
  <a href="#previous">&larr;</a>
</div>
<div id="next">
  <a href="#next">&rarr;</a>
</div>

到目前为止,这是JS:

$(document).ready(function() {
  var z = 0;
  var inAnimation = false;

  $('section.slide').each(function() {
    z++;
    $(this).css('z-index', z);
  });

  function swapFirstLast(isFirst) {
    if(inAnimation) return false;
    else inAnimation = true;

    var processZindex, direction, newZindex, inDeCrease;

    if(isFirst) {
      processZindex = z; direction = '-'; newZindex = 1; inDeCrease = 1;
    } else {
      processZindex = 1; direction = ''; newZindex = z; inDeCrease = -1;
    }

    $('section.slide').each(function() {
      if($(this).css('z-index') == processZindex) {
        $(this).animate({ 'top' : direction + $(this).height() + 'px' }, 'slow', function() {
          $(this).css('z-index', newZindex)
          .animate({ 'top' : '0' }, 'slow', function() {
            inAnimation = false;
          });
        });
      } else {
        $(this).animate({ 'top' : '0' }, 'slow', function() {
          $(this).css('z-index', parseInt($(this).css('z-index')) + inDeCrease);
        });
      }

      return false;
    }

    $('#next a').click(function() {
      return swapFirstLast(true);
    });

    $('#prev a').click(function() {
      return swapFirstLast(false);
    });
  });
});

我以为我可以在脚本中插入以下代码:

if($(this).css('z-index') == processZindex) {
  $(this).css('opacity', 1);
} else {
  $(this).css('opacity', 0.7);
}

问题是我似乎无法将不透明度设置为1以跟上z-index值为6.因此我考虑将$(this).css('z-index') == processZindex写为$(this).css('z-index') != 6,但问题出现了。

有没有更简单的方法对此进行编码?

1 个答案:

答案 0 :(得分:2)

我只是使用appendTopreprendTo使用元素的排序而不是z-index:

http://jsfiddle.net/jtbowden/RAT8N/1/

我无法确定一个功能或单独的功能是否更好。这是两个独立的功能:

http://jsfiddle.net/jtbowden/5LJcA/3/

这就是你想要的吗?