Jquery画廊下一个/上一个按钮

时间:2011-12-13 13:22:06

标签: javascript jquery button gallery

我半年前创建了一个jquery画廊(SO社区帮助了我很多因为我对js / jquery不够熟悉)现在我想在这个画廊添加下一个/上一个按钮。我尝试将它与其他画廊结合但没有任何正常工作。

这里是js:

<script type="text/javascript">
function showPic (whichpic) {
if (document.getElementById) {
$('#actimg').fadeOut(170);
setTimeout(function() {
document.getElementById('actimg').src = whichpic.href; 
$('#actimg').fadeIn(170);
}, 170);
return false; 
} else {
return true;
 } 
}
</script>

和html:

<img id="actimg" src="" width="600" height="400" alt="main" />

<a onclick="return showPic(this)" href="example_1.jpg">
<img height="39px" width="58px" src="example_1.jpg" alt="thumbnail" />
</a>

<a onclick="return showPic(this)" href="example_2.jpg">
<img height="39px" width="58px" src="example_2.jpg" alt="thumbnail" />
</a>

<a onclick="return showPic(this)" href="example_3.jpg">
<img height="39px" width="58px" src="example_3.jpg" alt="thumbnail" />
</a>

图库看起来像http://www.rafsimons.com/collections/aw-11/,但它不是闪光灯,现在我没有下一个/上一个按钮。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

首先为所有拇指(<a>标签)添加一个类属性,以便可以从jQuery轻松引用它们:

<a class="gallery_item" onclick="return showPic(this)" href="example_1.jpg">
<img height="39px" width="58px" src="example_1.jpg" alt="thumbnail" />
</a>
...

我们需要一种方法来了解哪一个是当前图像。我们可以将该信息存储在<a>标记本身的自定义属性中。为此,修改showPic函数,如:

function showPic (whichpic) {
  if (document.getElementById) {
    $('.gallery_item').removeAttr('current'); // <- remove 'current' attribute from all thumbs
    $('#actimg').fadeOut(170);
    setTimeout(function() {
      document.getElementById('actimg').src = whichpic.href; 
      $('#actimg').fadeIn(170);
      $(whichpic).attr('current', '1'); // <- set this one as current
    }, 170);
    return false; 
  } else {
    return true;
  }
}

现在为next / prev按钮添加2个链接,并将它们放在适当的位置。将他们的ID设为“下一个”和“上一个”

<a href="#" id="prev" onclick="return nextPic()">Prev</a>

<a href="#" id="next" onclick="return prevPic()">Next</a>

现在添加2个js函数nextPic()和prevPic(),如:

function nextPic() {
  var current = null;
  $('.gallery_item').each(function() {
    if($(this).attr('current')=='1') {
    current = $(this);
    return false;
    }
  });
  if(current!=null) {
    if(current.parent().next().length!=0) {
    showPic(current.parent().next().find('.gallery_item')[0]); // <- show next pic
    }
    else {
    showPic($('.gallery_item:first')[0]); // if no next pic, show first pic
    }
  }
  return false;
}

function prevPic() {
  var current = null;
  $('.gallery_item').each(function() {
    if($(this).attr('current')=='1') {
    current = $(this);
    return false;
    }
  });
  if(current!=null) {
    if(current.parent().prev().length!=0) {
    showPic(current.parent().prev().find('.gallery_item')[0]); // <- show next pic
    }
    else {
    showPic($('.gallery_item:last')[0]); // if no next pic, show first pic
    }
  }
  return false;
}

添加此项,默认情况下将第一个图像初始化为当前图像。

$().ready(function() {
  $('.gallery_item:first').attr('current', '1');
});
相关问题