jQuery 支持的显示/隐藏链接导致页面滚动
这里是 Javascript 和 jQuery 新手。我在主页中编写了一个链接,该链接应该切换其下方元素中文本块的可见性。这是 html,后面是实现显示/隐藏行为的 Javascript 块。
<a href="#hh_bibtex">Show BibTeX</a>
<div class="bibtex" id="hh_bibtex">
This text should appear and disappear.
</div>
<script type="text/javascript">
$("#hh_bibtex").hide();
$("[href='#hh_bibtex']").click(function(){
if ( $(this).html() == "Show BibTeX" ) {
$(this).html("Hide BibTeX");
$("#hh_bibtex").show();
} else {
$(this).html("Show BibTeX");
$("#hh_bibtex").hide();
}
});
</script>
这工作正常,除了一个非常烦人的怪癖:当我单击链接显示文本块时,不仅会出现文本,而且页面会立即向下滚动,以便“此文本应该出现并消失”位于最顶部浏览器窗口的。这非常让人迷失方向。幸运的是,相反的情况并非如此:当我单击链接以使文本消失时,窗口不会滚动。
我怎样才能消除这种不受欢迎的滚动?
Javascript and jQuery newbie here. I wrote a link in my homepage that's supposed to toggle the visibility of a block of text in a element below it. Here's the html, followed by the Javascript block that implements the show/hide behavior.
<a href="#hh_bibtex">Show BibTeX</a>
<div class="bibtex" id="hh_bibtex">
This text should appear and disappear.
</div>
<script type="text/javascript">
$("#hh_bibtex").hide();
$("[href='#hh_bibtex']").click(function(){
if ( $(this).html() == "Show BibTeX" ) {
$(this).html("Hide BibTeX");
$("#hh_bibtex").show();
} else {
$(this).html("Show BibTeX");
$("#hh_bibtex").hide();
}
});
</script>
This works ok, except with one very annoying quirk: when I click the link to show the text block, not only does the text appear, but the page instantly scrolls down so that "This text should appear and disappear" is at the very top of the browser window. It's very disorienting. Mercifully, the opposite is not true: when I click the link to make the text disappear, the window does not scroll.
How can I eliminate this unwelcome scrolling?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您进行一些跟进并提供找到答案的链接。对我来说,关键是放置:
event.preventDefault()
;就在单击事件之后,执行我的 jquery .show() 方法之前。Thank you for doing a little follow up and providing the link where you found your answer. For me the key was placing:
event.preventDefault()
; just right after the click event, and before executing my jquery .show() method.