单击停止脚本滚动回页面顶部
stop script from scrolling back to top of page onclick
我有一个简单的脚本,用于选项卡导航。它只是隐藏并显示一个div。然而,当我从一个选项卡切换到另一个选项卡时,屏幕总是向上平移到顶部!有人知道如何阻止这种情况吗?我的脚本如下:
<script type="text/javascript">
$(document).ready(function() {
//Default Action
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active content
return false;
});
});
</script>
我认为您的点击处理程序需要一个preventDefault()
。
这将阻止浏览器向顶部平移。
像这样:
//On Click Event
$("ul.tabs li").click(function(e) {
e.preventDefault();
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active content
return false;
});
尝试更改您的点击处理程序以针对<a/>
标记而不是<li/>
标记:
//On Click Event
$('ul.tabs li a').click(function() {
$('ul.tabs li').removeClass('active');
$(this).closest('li').addClass('active');
$('.tab_content').hide();
var activeTab = $(this).attr('href');
$(activeTab).fadeIn();
return false; // prevent default action of <a/> element
});
发生这种情况的原因是,即使在<li/>
标记的单击处理程序上返回false,<a/>
标记的单击事件也会弹出,并在包含在<li/>
标记中的同时被触发。由于没有点击处理程序阻止</a>
标记的默认操作,因此页面会跳到顶部——这是假设href属性以哈希开头。
我希望这能有所帮助!
相关文章:
- 单击顶部导航时如何进行向下滚动效果(向下滑动).
- 背景图像顶部的滚动图像不移动
- 滚动然后捕捉到顶部而不是取消捕捉
- 如何在从顶部滚动时暂停转盘/滑块,并在滚动到顶部时重新开始
- Android默认浏览器:谷歌地图制作“;位置:相对;元素在页面顶部滚动
- 如何将“切换滑块内容”的顶部滚动到视口的中心
- 修复了在页面顶部滚动时居中导航的问题
- 每次在顶部滚动顶部重置
- 为什么有时滚动顶部/滚动左不可写
- 当目标处于顶部滚动状态时,如何从菜单中激活项目
- 请在顶部滚动一次
- 当用户从顶部滚动超过一定距离时,执行Javascript
- 向表格添加水平顶部滚动条的Aurelia方式
- 如何使文档(页面)向左和顶部以及相对于正文的滚动(向左和顶部滚动)
- 从导航底部而非页面顶部滚动至Div
- 顶部滚动-可替代preventDefault()函数
- “无限scroll"代码只适用于顶部滚动
- 当导航栏固定顶部滚动时,引导捕获
- 单击时从窗口顶部滚动到特定位置
- 花式框弹出窗口始终在顶部滚动