用js做一个联系我们的页面
时间: 2024-05-07 11:22:13 浏览: 4
好,以下是一个简单的联系我们页面的示例,使用HTML、CSS和JavaScript编写:
```html
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
<style>
form {
display: flex;
flex-direction: column;
align-items: center;
margin: 50px auto;
padding: 20px;
background-color: #f4f4f4;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
input[type="text"],
input[type="email"],
textarea {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
border: none;
background-color: #ffffff;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
resize: none;
}
input[type="submit"] {
padding: 10px 20px;
background-color: #333333;
color: #ffffff;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #555555;
}
</style>
</head>
<body>
<form>
<h2>Contact Us</h2>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Enter your message" required></textarea>
<input type="submit" value="Send">
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const message = document.getElementById('message').value;
// Send the form data to the server using an AJAX request
const xhr = new XMLHttpRequest();
xhr.open('POST', '/send-email.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(`name=${name}&email=${email}&message=${message}`);
// Display a message to the user indicating success or failure
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
alert('Your message has been sent!');
form.reset();
} else if (this.readyState === 4 && this.status !== 200) {
alert('There was an error sending your message. Please try again later.');
}
};
});
</script>
</body>
</html>
```
这个页面包括一个表单,用户可以输入他们的姓名、电子邮件地址和消息。当用户单击“发送”按钮时,JavaScript将使用AJAX将表单数据发送到服务器上的`send-email.php`脚本。如果成功发送邮件,则会向用户显示成功消息,并清除表单。否则,将向用户显示错误消息。请注意,这只是一个简单的示例,实际上需要更多的服务器端代码来发送电子邮件。