javascript锚点避免在点击时滚动到顶部 [英] javascript anchor avoid scroll to top on click

查看:132
本文介绍了javascript锚点避免在点击时滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中创建了一个函数,我将其添加到锚点

I created a function in javascript that i add to an anchor as such

javascript:

javascript :

somefunction = function () {alert('foo')}

html:

<a href="#" onclick="return somefunction()">anchor</a>

每次我点击该功能执行的锚点,但屏幕滚动到顶部

everytime i click on the anchor the function executes but the screen scrolls to the top

我知道我可以这样做

<a href="javascript:void(0)" onclick="return somefunction()">anchor</a>

但我看到第一个选项在没有向上滚动的情况下实现了

but I have seen the first option implemented without this hick up of scrolling up

有什么诀窍吗?

谢谢

推荐答案

onclick导致页面重新提交,因此滚动到顶部。

The onclick causes the page to resubmit, therefore scrolling to the top.

你需要onclick事件返回false以避免回发。

You need the onclick event to return a false in order to avoid the postback.

这可以通过更改函数返回false来完成:

This can be done by changing your function to return a false:

somefunction = function () {alert('foo'); return false;}

或者更改链接和onClick事件:

Or to change the link and onClick event to do so:

<a href="javascript:void(0)" onclick="somefunction(); return false;">anchor</a>

这篇关于javascript锚点避免在点击时滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆