【问题标题】:Contact Form in html/csshtml/css 中的联系表格
【发布时间】:2021-12-28 20:23:10
【问题描述】:

您好,我有以下联系方式代码:

/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type=submit]:hover {
  opacity: 0.9;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="thankyou.html" method="POST" novalidate>
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>
            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

我想稍微修改一下这个表单,只改变输入字段。基本上,我想在输入字段上添加动画。

预期输出

https://watch.screencastify.com/v/5kecEAtHg4o2VXpDpEYU

如您所见,我希望消息显示在输入字段中,但是当用户单击输入字段时,消息应显示在输入字段的顶部,如视频所示。关于如何完成这项任务的任何建议?

这是视频中联系方式的代码:

Contact.jsx:

/ dependancies
import React from 'react'
import { Grid, Typography, TextField, Button, Divider, useMediaQuery } from '@material-ui/core'
import emailjs from 'emailjs-com'

// icons
import { FaGithub, FaLinkedin, FaPhone } from 'react-icons/fa'
import { MdEmail } from 'react-icons/md'

// file imports
import { db } from "../../firebaseConfig";
import ContactStyles from './ContactStyles'

import{ init } from 'emailjs-com';
init(process.env.REACT_APP_USER_ID);

const Contact = () => {
    // classes and queries
    const classes = ContactStyles();
    const md = useMediaQuery('(max-width: 960px)');
    const lg = useMediaQuery('(min-width: 960px)');

    // state declaration
    const [name, setName] = React.useState("");
    const [email, setEmail] = React.useState("");
    const [message, setMessage] = React.useState("");
    const [errorName, setErrorName] = React.useState(false);
    const [errorEmail, setErrorEmail] = React.useState(false);
    const [errorMessage, setErrorMessage] = React.useState(false);

    // event handler
    const submitHander = (e) => {
        e.preventDefault(); // prevents screen refresh
        // uses regex to verify email
        const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        setErrorName(false);
        setErrorEmail(false);
        setErrorMessage(false);

        // if a field is invalid, ensure that email is not submitted and error is thrown
        if (name === "" || !emailRegex.test(email) || message === "") {
            if (name === "") {
                setErrorName(true);
            }

            if (!emailRegex.test(email)) {
                setErrorEmail(true);
            }

            if (message === "") {
                setErrorMessage(true);
            }
        } else {
            const firebaseObject = { // object to be sent to firebase and email
                name: name,
                email: email,
                message: message
            }

            // send to firebase
            db.collection('contacts').add(firebaseObject)
                .then(() => {
                    console.log('submitted to Firebase');
                })
                .catch((err) => {
                    console.log(err.message);
                });

            // send to email
            emailjs.send(process.env.REACT_APP_SERVICE_ID, process.env.REACT_APP_TEMPLATE_ID,{
                name: name,
                email: email,
                to_name: "",
                from_name: "",
                message: message,
                })
                .then((response) => {
                    alert('Message has been submitted!');
                    console.log(response);
                })
                .catch((err) => {
                    console.log(err);
                });

            setName('');
            setEmail('');
            setMessage('');
            setErrorName(false);
            setErrorEmail(false);
            setErrorMessage(false);
        }
    }

    return (
        <Grid container className={classes.root} id="contact">
            {/* Title */}
            <Grid className={classes.title} item xs={12}>
                <br />
                <Typography variant="h2">Contact Me</Typography>
                <Typography variant="h4">- Can't Wait to Connect! -</Typography>
            </Grid>

            {/* Contact Text */}
            {lg && <>
                <Grid item xs={1}></Grid>
            <Grid item xs={10} md={5}>
                <br /><br />
                <Typography variant="h5"><b>Get in Touch!</b></Typography>
                <Divider></Divider>
                <br />
                <MdEmail />&nbsp;
                <Typography display="inline"><b> Email:</b></Typography>
                <a rel="noreferrer" target="_blank" className={classes.contact} href="mailto:anjaligta@outlook.com">
                    <Typography display="inline"> anjaligta@outlook.com</Typography>
                </a>
                <div /><br />
                <FaPhone />&nbsp;
                <Typography display="inline"><b> Phone:</b></Typography>
                <a rel="noreferrer" target="_blank" className={classes.contact} href="647-544-0781">
                    <Typography className={classes.contact}  display="inline"> 647-544-0781</Typography>
                </a>
                <div /><br />
                <FaGithub />&nbsp;
                <Typography display="inline"><b> Github:</b></Typography>
                <a rel="noreferrer" target="_blank" className={classes.contact} href="https://github.com/anjalig21">
                    <Typography  display="inline"> github.com/AnjaliGupta</Typography>
                </a>
                <div /><br />
                <FaLinkedin />&nbsp;
                <Typography display="inline"><b> LinkedIn:</b></Typography>
                <a rel="noreferrer" target="_blank" className={classes.contact} href="https://www.linkedin.com/in/anjali-gupta21/">
                    <Typography  display="inline"> linkedin.com/in/AnjaliGupta</Typography>
                </a>
                <br /><br /><br />
            </Grid>
            <Grid item xs={1}></Grid>
            </>}

            {/* Contact Form */}
            {md && <Grid item xs={1}></Grid>}
            <Grid item xs={10} md={4}>
                <div className={classes.formContainer}>
                    <form onSubmit={submitHander} className={classes.form}>
                        <TextField
                            className={classes.input}
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            label="Name"
                            variant="outlined"
                            error={errorName}
                            helperText={errorName ? "Please enter a name." : ""}
                        />
                        <br /><br />
                        <TextField
                            className={classes.input}
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            label="Email"
                            variant="outlined"
                            error={errorEmail}
                            helperText={errorEmail ? "Please enter a correct email." : ""}
                        />
                        <br /><br />
                        <TextField
                            className={classes.input}
                            value={message}
                            onChange={(e) => setMessage(e.target.value)}
                            label="Message"
                            multiline
                            rows={10}
                            variant="outlined"
                            error={errorMessage}
                            helperText={errorMessage ? "Please enter a message." : ""}
                        />
                        <br /><br />
                        <div className={classes.center}>
                            <Button type="submit" variant="contained" size="large" className={classes.button}>
                                Submit
                            </Button>
                        </div>
                    </form>
                </div>
            </Grid>
            <Grid item xs={1}></Grid>
        </Grid>
    )
}

export default Contact;

ContactStyles.jsx:

import { makeStyles } from '@material-ui/styles';

const ContactStyles = makeStyles((theme) => ({
    root: {
        background: theme.palette.primary.dark
    },
    title: {
        textAlign: "center",
        color: theme.palette.secondary.dark
    },
    formContainer: {
        height: "78vh",
        position: "relative"
    },
    form: {
        position: "absolute",
        top: "50%",
        left: "50%",
        transform: "translate(-100%, -50%)"
    },
    input: {
        width: "200%",
        fontWeight: "600",
        '& label.Mui-focused': {
      color: theme.palette.secondary.dark,
    },
    '& .MuiInput-underline:after': {
      borderBottomColor: theme.palette.secondary.dark,
    },
    '& .MuiOutlinedInput-root': {
      '& fieldset': {
        borderColor: '#0644A3',
      },
      '&:hover fieldset': {
        borderColor: theme.palette.secondary.dark,
      },
      '&.Mui-focused fieldset': {
        borderColor: theme.palette.secondary.dark,
      },
    },
    },
    center: {
        display: "flex",
        justifyContent: "center",
        width: "200%"
    },
    button: {
        backgroundColor: "#0644A3",
        color: "#FFFFFF",
        borderRadius: 20,
        marginRight: "2%",
        textTransform: "none",
        "&:hover": {
            transition: "0.3s",
            color: "#0644A3",
            backgroundColor: "#FFFFFF",
            border: "1px solid #0644A3",
        }
    },
    contact: {
        textDecoration: "none",
        color: "#000000",
        "&:hover": {
            transition: "0.3s",
            color: "#b5befa"
        }
    },
    spacing: {
        display: "flex",
        alignItems: "center"
    }
}))

export default ContactStyles;

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    我尝试为您创建一个测试版,使用您链接的视频作为参考

    仅使用 HTML 和 CSS...

    这里的诀窍是创建一个 Extra Div 作为父级,因此我们可以将标签和输入放入其中。

    现在将父级设置为position: relative;,因此标签将为absolute

    现在我们可以成功地使用 TOP、LEFT、RIGHT、BOTTOM 了(将标签定位为占位符)

    我把逻辑放在这里.input-container input:focus~label

    * {
      --input-height: 3rem;
    }
    
    section {
      height: 100vh;
      width: 100vw;
      display: grid;
      place-content: center;
    }
    
    .input-container input {
      height: var(--input-height);
      width: 80vw;
      font-size: 2rem;
    }
    
    .input-container {
      position: relative;
      display: grid;
      place-items: center start;
    }
    
    .input-container label {
      position: absolute;
      left: 1rem;
      font-size: 1.5rem;
      color: rgb(90, 90, 90);
      background-color: white;
      transition-duration: 0.5s;
    }
    
    .input-container input:focus~label {
      position: absolute;
      font-size: 0.7rem;
      top: -0.6rem;
      padding: 0.2em;
      left: 0.5rem;
      color: rgb(0, 81, 255);
      background-color: white;
      transition-duration: 0.2s;
      z-index: 2;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <link rel="stylesheet" href="style.css">
    </head>
    
    <body>
      <section>
        <form action="">
          <div class="input-container">
            <input type="text" name="" id="my-input">
            <label for="my-input">hello world</label>
          </div>
        </form>
      </section>
    </body>
    
    </html>

    【讨论】:

    • 谢谢!我可以以此为指导
    • 希望对你有帮助
    • 什么类导致了动画?
    • 是使用过渡,很简单(不需要类)有效地缩小文本的代码在这里.input-container input:focus~label
    • 确保标签写在 HTML 输入之后,但在父 div 内
    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 2013-11-02
    • 2020-06-06
    • 2020-12-24
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多