HTML表单元素之<input />

定义

input元素是基于Web的表单创建交互式控件,方便接受来自用户的数据。

默认style

  • 行内块元素display: inline-block;
  • 具有边框border属性
  • 获取焦点的时候,默认是通过outline属性进行控制。

重要属性

  • type:input标签的工作方式由type属性决定。
取值 解释
text 单行文本区域、输入的文本可见【默认值】
password 单行文本区域,输入的文本被遮盖
number 输入数字的控件
radio 单选按钮,多个拥有相同name值的选项中选择一个
checkout 复选框
button 没有默认行为的按钮,按钮中的值显示其value属性的值
file 上传文件
  • name:input表单控件的名字【没有name属性时,不会一起提交表单】
  • value:值
  • size:默认值为20。仅指定一次可以看到多少个字符【与minlength和maxlength区分】。类似控制input的width。
  • minlength - maxlength:能够接受输入的最小-最大字符数
  • pattern:验证文本框的正则表达式
  • placeholder:简短的提示信息
  • disabled:布尔值。表示控件是否被禁用。【禁用的表单元素不会一起提交】
  • readonly:布尔值。表示控件是否可以编辑。【只读的表单元素将会一起提交】
  • required:布尔值。表示此值为必填项提交前必须检查该值

案例:

<!DOCTYPE html>
<html>
    <head>
        <title>input中type为text</title>
    </head>
    <body>
        <form>
            <div>
                <label for="uname1">username1: </label>
                <input type="text" id="uname1">
            </div>
            <div>
                <label for="uname2">username2: </label>
                <input type="text" id="uname2" name="name2">
            </div>
            <div>
                <label for="uname3">username3: </label>
                <input type="text" id="uname3" name="name3" placeholder="请输入用户名">
            </div>
            <div>
                <label for="uname4">username4: </label>
                <input type="text" id="uname4" name="name4" value="请输入用户名">
            </div>
            <div>
                <label for="uname5">username5: </label>
                <input type="text" id="uname5"  name="name5" minlength="1" maxlength="5">
            </div>
            <div>
                <label for="uname6">username6: </label>
                <input type="text" id="uname6"  name="name6" minlength="1" maxlength="5" required>
            </div>
            <div>
                <label for="uname7">username7: </label>
                <input type="text" id="uname7"  name="name7" disabled>
            </div>
            <div>
                <label for="uname8">username8: </label>
                <input type="text" id="uname4" name="name8" readonly>
            </div>
            <div>
                <label for="uname9">username9: </label>
                <input type="text" id="uname9" name="name9" size="30">
            </div>
            <div>
                <button>Submit</button>
            </div>
        </form>
    </body>
</html>

结果:


input中的常用属性.gif

input中的校验

一些伪类可用于设置表单元素的样式,以帮助用户查看其值是有效还是无效。即:valid(有效)和:invalid(无效)。

<!DOCTYPE html>
<html>
    <head>
        <title>input中type为text</title>
        <style type="text/css">
            div {
                margin-bottom: 10px;
                position: relative;
            }

            input+span {
                padding-right: 30px;
            }

            input:invalid+span:after {
                position: absolute;
                content: '✖';
                padding-left: 5px;
            }

            input:valid+span:after {
                position: absolute;
                content: '✓';
                padding-left: 5px;
            }
        </style>
    </head>
    <body>
        <form>
            <div>
                <label for="uname">Choose a username: </label>
                <input type="text" id="uname" name="name" minlength="2" required>
                <span></span>
            </div>
            <div>
                <button>Submit</button>
            </div>
        </form>
    </body>
</html>

结果:


input校验.png

使用

type="text"

作用:创建基本的单行输入。
属性:【以上列举的重要属性除外】

  • pattern:匹配正则表达式【不需要使用required属性就能够影响伪类】

type="password"

作用:作为一行纯文本编辑器控件呈现,其中文本被"(*)"或"(·)"等符号替换。


type=password的基本样式.png

属性:

  • autocomplete:可以让密码管理器自动输入密码。
    取值:on、off、current-password、new-password
  • inputmode:指定输入模式
    取值:text、numeric、tel、url、email
  • pattern:添加正则表达式的验证。

type="number"

作用:让用户输入一个数字,包含内置样式以拒绝非数字的输入。当此元素获取焦点之后,将会出现步进的箭头,方便用户操作。


type=number的最初样式.png

属性:

  • step:此属性可以设置步长的值。【可以是整数也可以是小数】
  • min/max:指定该字段的最大和最小值。
  • pattern:当type=number的时候,pattern属性将会失效,只需要使用min/max属性来控制即可。
  • size:此属性将会失效,我们只能通过css的width属性来控制input框的大小。
  • list:指定该属性来从中进行选择,该列表属性包含<datalist>的ID作为其值。

案例:list属性

<!DOCTYPE html>
<html>
    <head>
        <title>input中type为text</title>
        <style type="text/css">
            div {
                margin-bottom: 10px;
                position: relative;
            }

            input+span {
                padding-right: 30px;
            }

            input:invalid+span:after {
                position: absolute;
                content: '✖';
                padding-left: 5px;
            }

            input:valid+span:after {
                position: absolute;
                content: '✓';
                padding-left: 5px;
            }
        </style>
    </head>
    <body>
        <form>
            <input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers">
            <span class="validity"></span>
            
            <datalist id="defaultNumbers">
              <option value="10045678">
              <option value="103421">
              <option value="11111111">
              <option value="12345678">
              <option value="12999922">
            </datalist>
        </form>
    </body>
</html>

结果:


<datalist>a和list属性的初次使用.png

type="radio"

作用:单选按钮,允许在多个拥有相同的name的选项中选择其中一个。
注意事项:

  • 一个单选按钮组:有相同name属性的单选按钮组成。
  • 每个单选按钮必须有value属性,否则提交的表单数据将只有name,没有对应的值。
  • 默认选中的按钮:使用checked属性进行控制
<!DOCTYPE html>
<html>
    <head>
        <title>input中type为radio</title>
    </head>
    <body>
        <form>
            <p>Please select your preferred contact method:</p>
            <div>
                <input type="radio" id="contactChoice1" name="contact" value="email">
                <label for="contactChoice1">Email</label>
                <input type="radio" id="contactChoice2" name="contact" value="phone">
                <label for="contactChoice2">Phone</label>
                <input type="radio" id="contactChoice3" name="contact" value="mail">
                <label for="contactChoice3">Mail</label>
            </div>
            
            <input type="text" id="contactChoice3" name="name">
            <label for="contactChoice3">Name</label>
            <div>
                <button type="submit">Submit</button>
            </div>
        </form>
        <pre id="log">
        </pre>

        <script type="text/javascript">
            var form = document.querySelector("form");
            var log = document.querySelector("#log");

            form.addEventListener("submit", function(event) {
                var data = new FormData(form);
                var output = "";
                console.dir(data)
                for (const entry of data) {
                    console.log(entry)
                    output += entry[0] + "=" + entry[1] + "\r";
                };
                log.innerText = output;
                event.preventDefault();
            }, false);
        </script>

    </body>
</html>

结果:


type=radio和FormData的初次使用.png

type="checkout"

作用:定义一个复选框,可以设定为选中或者未选中。
注意事项:

  • name:type=checkbox时,name的值可以不同,可以相同,后台可以组成一个Array。【type=radio的时候,name的值是一定相同的】
  • value:value的值如果没有填写,默认为"on",建议添加value属性
  • checked:checkbox的默认选中的由checked属性决定。
    案例:type=checkbox
<!DOCTYPE html>
<html>
    <head>
        <title>input中type为radio</title>
    </head>
    <body>
        <form>
            <p>Choose your monster's features:</p>

            <div>
                <input type="checkbox" id="scales" name="checkbox" value="Scales">
                <label for="scales">Scales</label>
            </div>

            <div>
                <input type="checkbox" id="horns" name="checkbox" value="Horns">
                <label for="horns">Horns</label>
            </div>
            <button type="button">submit</button>
        </form>
        <pre id="log">
        </pre>

        <script type="text/javascript">
            var form = document.querySelector("form");
            var log = document.querySelector("#log");
            var button = document.querySelector("button")
            
            button.addEventListener("click", function(event) {
                var data = new FormData(form);
                var output = "";
                for (const entry of data) {
                    console.log(entry)
                    output += entry[0] + "=" + entry[1] + "\r";
                };
                log.innerText = output;
                event.preventDefault();
            }, false);
        </script>

    </body>
</html>

结果:


type=checkbox.png

type="button"

作用:创建一个没有默认行为的按钮;显示的值通过value属性控制,默认为空。【h5中通过<button>取代】。type还可以指定为其他值,如:"submit"【提交】、"reset"【重置】,设置为此类型之后就有了默认的行为。
属性:

  • form:与当前页面的<form>标签进行绑定。取值为form标签中的id属性值。如果<input type-'submit' /><form>中,可以不指定form属性,默认与当前form关联。
  • formenctype:指定提交的内容的格式,取值有application/x-www-form-urlencodedmultipart/form-datatext/plain等【将会覆盖form中的action属性】
  • formaction:处理按钮提交的路径【将会覆盖form中的action属性】
  • formmethod:指定提交的方式:取值有postget、‘put’【将会覆盖form中的method】
  • formtarget:表示接收提交的表单后在哪里显示,取值有_self_blank_parent_top

案例

<!DOCTYPE html>
<html>
    <head>
        <title>input中type为radio</title>
    </head>
    <body>
        <form>
            <p>Please select your preferred contact method:</p>
            <div>
                <input type="radio" id="contactChoice1" name="contact" value="email">
                <label for="contactChoice1">Email</label>
                <input type="radio" id="contactChoice2" name="contact" value="phone">
                <label for="contactChoice2">Phone</label>
                <input type="radio" id="contactChoice3" name="contact" value="mail">
                <label for="contactChoice3">Mail</label>
            </div>
            
            <input type="text" id="contactChoice3" name="name">
            <label for="contactChoice3">Name</label>
            
            <div>
                <input type="submit" value="Submit" />
            </div>
        </form>
        <pre id="log">
        </pre>

        <script type="text/javascript">
            var form = document.querySelector("form");
            var log = document.querySelector("#log");

            form.addEventListener("submit", function(event) {
                var data = new FormData(form);
                var output = "";
                console.dir(data)
                for (const entry of data) {
                    console.log(entry)
                    output += entry[0] + "=" + entry[1] + "\r";
                };
                log.innerText = output;
                event.preventDefault();
            }, false);
        </script>

    </body>
</html>

结果:


type=button的运行结果.png

<button></button>元素

作用:表示是一个可点击的按钮,可以用在表单或文档其他需要使用简单标准按钮的地方。
属性:button的属性和<input type="button" />中的属性基本一致,

  • type: 设置button的类型。取值有buttonsubmitresetmenu【打开一个指定<menu>元素定义的菜单】
注意事项

1、<button><input />更容易使用样式。<input>只能使用文本样式,<button>能使用HTML内容
2、如果按钮不是向服务器提交数据,保证<button>中的type为button。·

type="file"

作用:用户可以选择一个或多个文件以提交表单的方式上传到服务器上,或者通过JavaScript的File API对文件进行操作。
附加属性:

  • accept:定义了文件input应该接受的文件类型。有多种类型的时候,使用逗号进行分割。取值有:
    .开头的合法的文件名拓展名【指定单个】、
    一个不带拓展名的MIME类型字符串、
    字符串audio/*video/*image/*【指定一类】
  • capture:捕获图像或视频数据的源,如指定使用哪个摄像头去获取数据。
  • files:被选择的文件以HTMLInputElement.files属性返回,值的类型是FileList对象。即所有选择的文件。
  • multiple:布尔属性,表示用户可以选择多个文件。

注意事项

  1. accept属性不验证所选文件的类型,只是为浏览器提供指示来引导用户选择正确的文件类型。
  2. 出于安全原因,源文件的实际路径没有显示在input的value属性中,显示的内容为C:\fakepath\+文件名

案例:

<!DOCTYPE html>
<html>
    <head>
        <title>input中type为radio</title>
        <style type="text/css">
            label {
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <div>
                <label for="image_uploads">Choose images to upload (PNG, JPG)</label>
                <input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple>
            </div>
            <div class="preview">
                <p>No files currently selected for upload</p>
            </div>
            <div>
                <button>Submit</button>
            </div>
        </form>

        <script type="text/javascript">
            // 实际的输入框
            const input = document.querySelector('input');
            input.style.opacity = 0; // 不使用 visibility: hidden 或者 display: none,因为辅助技术将后两种样式解释为文件 input 是不可交互的。
            // 选中文件的提示框
            const preview = document.querySelector('.preview');
            // 接收的文件的类型
            const fileTypes = [
                'image/jpeg',
                'image/pjpeg',
                'image/png'
            ];
            
            // 添加input的change事件
            input.addEventListener("change", updateImageDisplay)

            // 验证文件类型的函数
            function validFileType(file) {
                return fileTypes.includes(file.type);
            }
            
            // 大小转化
            function returnFileSize(number) {
              if(number < 1024) {
                return number + 'bytes';
              } else if(number >= 1024 && number < 1048576) {
                return (number/1024).toFixed(1) + 'KB';
              } else if(number >= 1048576) {
                return (number/1048576).toFixed(1) + 'MB';
              }
            }
            
            // input中change的回调函数
            function updateImageDisplay() {
                // 先清空提示框中的内容
                while (preview.firstChild) {
                    preview.removeChild(preview.firstChild); // js操作DOM值移除子元素
                }

                const curFiles = input.files;
                if (curFiles.length === 0) { // 没有选中文件
                    const para = document.createElement('p'); // js操作DOM之创建元素
                    para.textContent = 'No files currently selected for upload';
                    preview.appendChild(para); // js操作DOM之添加子元素
                } else {
                    const list = document.createElement('ol');
                    preview.appendChild(list);

                    for (const file of curFiles) {
                        const listItem = document.createElement('li');
                        const para = document.createElement('p');
                        if (validFileType(file)) {
                            para.textContent = `File name ${file.name}, file size ${returnFileSize(file.size)}.`;
                            const image = document.createElement('img');
                            image.src = URL.createObjectURL(file);

                            listItem.appendChild(image);
                            listItem.appendChild(para);
                        } else {
                            para.textContent = `File name ${file.name}: Not a valid file type. Update your selection.`;
                            listItem.appendChild(para);
                        }

                        list.appendChild(listItem);
                    }
                }
            }
        </script>

    </body>
</html>

运行截图


type=file.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容