123456789101112131415161718192021222324252627282930313233343536373839404142 |
- <!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>
- <style>
- .demo{
- background-color: yellow;
- }
- </style>
- </head>
- <body>
- <button id="btn">点我创建一个输入框</button>
- <script>
- // 获取按钮
- const btn = document.getElementById('btn')
- // 绑定点击事件
- btn.onclick=()=>{
- // 创建input元素,括号内是元素名
- const input = document.createElement('input')
- input.className = 'demo' //设置样式
- input.value = 99 //指定初始值
- input.onclick = () =>{alert(1)} //绑定点击事件
- // 将元素放入页面(直接放入body)
- document.body.appendChild(input)
- // input框出现的时候自动获取焦点
- input.focus()
- input.parentElement.style.backgroundColor = 'skyblue'
- }
- </script>
- <!--
- 自动获取焦点要放在向页面添加元素的代码后面才有效果,如果放在添加元素
- 之前,则不会获取焦点
- 获取父元素也需要在向页面添加元素之后才能获取
- 但是设置样式、指定初始值、绑定点击事件都可以放在添加元素之前
- -->
- </body>
- </html>
|