【问题标题】:How to prevent page from jumping to top of page with mailto link in an anchor?如何使用锚点中的​​ mailto 链接防止页面跳转到页面顶部?
【发布时间】:2018-12-12 18:33:44
【问题描述】:

我有一个以mailto:example@email.com 为href 的锚链接,但单击它时会跳转到页面顶部。我想防止这种情况发生。

我在我的 js 中尝试了e.preventDefault(),它可以工作,但问题是它不再打开电子邮件客户端。

场景:

我的页面底部有一个“取得联系”链接。它应该打开电子邮件客户端(正在工作)。问题是每次点击它都会跳转到页面顶部。有没有办法防止这种情况发生?

这是锚链接的样子:

<a class="get-in-touch" href="mailto:email@gmail.com">Get In Touch</a>

这是我已经尝试过的。

$(".get-in-touch").on("click",function(e){
    e.preventDefault();
    window.location.href = $(this).attr("href");
});

但这没有用。仍然跳转到页面顶部。

【问题讨论】:

  • 在函数中尝试 e.preventDefault()
  • 请将问题的minimal, complete and verifiable example 放在一起,以便我们可以准确地看到您遇到的问题并可能会尝试帮助您。
  • click 事件中使用e.preventDefault(),然后在同一事件中使用window.location.href="your link"
  • @Code_Ninja 已经试过了,还是不行,还是跳到页首。
  • @Code_Ninja 感谢您的回复,如果您有其他想法请告诉我,我将不胜感激。谢谢!

标签: jquery html


【解决方案1】:

而不是写:

<a class="get-in-touch" href="mailto:email@gmail.com">Get In Touch</a>

写下:

<a class="get-in-touch" href="#" onclick="window.open('mailto:email@gmail.com')">Get In Touch</a>

这肯定会奏效。

Here 是关于您的问题的另一个 stackoverflow 问题。

这是jsfiddle的链接。

【讨论】:

  • 它有效,非常感谢。非常感谢您的努力
  • 如果您找到了解决方案,请选择一个答案或支持/反对。
猜你喜欢
  • 2011-03-16
  • 2013-09-18
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多