使用#href使用div ID交换图库图像时如何防止页面跳转?

时间:2012-08-20 22:34:56

标签: css html hash gallery href

我一直在努力解决问题。我已经使用CSS制作了一个简单的html库,并且#href基本上换掉了包含图库的不同div ID。问题是,当您在图库中选择“下一个”或“上一个”按钮时,它会在浏览器中向上跳转页面,以便图库在页面顶部对齐。有没有人有任何想法如何防止这种情况?

以下是图库的代码:

<div id="pic1">
<img src="click/pic1.jpg" alt="" />
<a class="previous" href="#pic10"><b>Previous</b></a><a class="next" href="#pic2"><b>Next</b></a>
</div>
<div id="pic2">
<img src="click/pic2.jpg" alt="" />
<a class="previous" href="#pic1"><b>Previous</b></a><a class="next" href="#pic3"> <b>Next</b></a>
</div>
<div id="pic3">
<img src="click/pic3.jpg" alt="" />
<a class="previous" href="#pic2"><b>Previous</b></a><a class="next" href="#pic4"><b>Next</b></a>
</div>
<div id="pic4">
<img src="click/pic4.jpg" alt="" />
<a class="previous" href="#pic3"><b>Previous</b></a><a class="next" href="#pic5">  <b>Next</b></a>
</div>
<div id="pic5">
<img src="click/pic5.jpg" alt="" />
<a class="previous" href="#pic4"><b>Previous</b></a><a class="next" href="#pic6"><b>Next</b></a>
</div>
<div id="pic6">
<img src="click/pic6.jpg" alt="" />
<a class="previous" href="#pic5"><b>Previous</b></a><a class="next" href="#pic7"><b>Next</b></a>
</div>
<div id="pic7">
<img src="click/pic7.jpg" alt="" />
<a class="previous" href="#pic6"><b>Previous</b></a><a class="next" href="#pic8"><b>Next</b></a>
</div>
<div id="pic8">
<img src="click/pic8.jpg" alt="" />
<a class="previous" href="#pic7"><b>Previous</b></a><a class="next" href="#pic9"><b>Next</b></a>
</div>
<div id="pic9">
<img src="click/pic9.jpg" alt="" />
<a class="previous" href="#pic8"><b>Previous</b></a><a class="next" href="#pic10"><b>Next</b></a>
</div>
<div id="pic10">
<img src="click/pic10.jpg" alt="" />
<a class="previous" href="#pic9"><b>Previous</b></a><a class="next" href="#pic1">  <b>Next</b></a>
</div>

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

不是链接到#,而是链接到javascript:void(0);

<a class="previous" href="javascript:void(0);">Next</a>

或者,使用Javascript

阻止默认事件
$("a.previous, a.next").on("click", function(e) {
   e.preventDefault();
});

答案 1 :(得分:0)

设置

后需要使用JQuery
<a class="previous" href="javascript:void(0);">Next</a>

然后调用JS:

$(document).ready(function(){

    $('a.previous').click(function(e){
        var picID= parseInt($(this).parent().attr("id").substr(3));//gets the pic id count
        $("#pic"+(picID)).hide(); //hide the current div
        $("#pic"+(picID-1)).show(); //show the previous div
    });

    $('a.next').click(function(e){
        var picID= parseInt($(this).parent().attr("id").substr(3)); //gets the pic id count
        $("#pic"+(picID)).hide(); //hide the current div
        $("#pic"+(picID+1)).show(); //show the previous div
    });

});

请参阅:http://jsfiddle.net/uZ6g5/