简体   繁体   中英

Use <div> as a button and trigger a mailto when it is clicked

I'm creating a custom button on my webpage which actually is a <div> , I want to trigger a mailto when the button is clicked. What is the best way out?

I've tried calling a javascript function using-onClick that looks like this -

function foo(){
    window.open("mailto:xyz@abc.com");
}

But that opens a new tab in Chrome first, and then asks for the relevant app to send out the email. This experience is different from what we generally get when we simply do a <a href=mailto:.....> in HTML.

I can also create a new document element in the JS function, and simulate a click like this -

function sendEmail() {
    var mail = 'mailto:contact@test.com';
    var a = document.createElement('a');
    a.href = mail;
    a.click();
};

But i'm not too sure if that's the right way! Anyone has a better solution?

Try this, and tell me if works. If not, I will delete answer.

<script>
function sendEmail() 
{
    window.location = "mailto:xyz@abc.com";
}
</script>
<div onclick="sendEmail();">Send e-mail</div>

我知道参加聚会非常晚,但是如何将这些答案组合成更简单、更实用的东西:

<div class="button" onclick="location.href='mailto:xyz@abc.com';">Send E-Mail</div>

Use an anchor tag but change the display property to block:

HTML

<a class="mailto" href="mailto:contact@test.com">Mail</a>

CSS

.mailto{
  display:block;
  width:100px;
  height:20px;
}

This worked for me:

<script>
function sendEmail() 
{
    window.location.assign("mailto:xyz@abc.com");
}
</script>
<div onclick="sendEmail();">Send e-mail</div>

@Tony has used the same approach just assign has been added.

Try this function and html. It will open a new email client with.

<div onclick="doMail();">


function doMail() {

    var email ="xyz@abc.com";
    location.href = "mailto:"+email;
}

In order to obfuscate your email from SPAM bots that scan website for emails, you can do the following,

<div class="button" onclick="location.href='mail'+'to:xyz'+'@'+abc'+'.'+'com';">Send E-Mail</div>

and instead of the 'Send E-Mail' text you can place an image of your actual email address (screenshot) to make it more obvious.

<div onclick="mailtoperformingFunction('inner');" id="divbutton">

<script type="text/javascript">
function mailtoperformingFunction()
{
}
</script>

尝试这个 :

<div class="button" href="javascript: void(0)" onclick="location.href='mailto:abc@xyz.com';">Click to Send email</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM