首页 > 解决方案 > 通过点击“mailto”链接跳转到页面顶部

问题描述

我使用此 javaScript 代码将“mailto”添加到页面上的元素:

document.getElementById("mailTo").href = "mailto:?subject=look at this website&body=Hi,I found this website and thought you might like it "+ document.location.href

现在,当我点击链接时,它打开电子邮件就好了,但它也突然跳到页面顶部,谁能告诉我为什么会这样?或者我怎样才能阻止这种行为?

标签: javascriptbrowserscrollmailto

解决方案


我会从链接中删除原始的 onClick 事件,并创建一个新函数来处理点击。这应该可以防止来自常规 a-tag 的不需要的行为,我猜你的按钮是?

类似的东西;

document.getElementById('mailTo').removeAttribute("onclick");

document.getElementById('mailTo').onclick = function(){
    location.href = "mailto:?subject=look at this website&body=Hi,I found this website and thought you might like it "+ document.location.href;
};

关于“preventDefault();”的文档 这里也可以证明是有价值的: https ://www.w3schools.com/jsref/event_preventdefault.asp


推荐阅读