提交表单数据:
通过表单提交:
<form action="https://www.imooc.com/api/http/search/suggest?words=js" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="username"/>
<input type="text" name="password"/>
<input type="submit" value="提交" />
</form>
按下提交按钮,浏览器将自动发出请求,携带输入的数据跳转到 action 指定的页面。
通过 Ajax 提交:
<form id="login" action="https://www.imooc.com/api/http/search/suggest?words=js" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="username"/>
<input type="text" name="password"/>
<input type="submit" value="提交" id="submit" />
</form>
const login = document.getElementById('login')
const {username, password} = login
const btn = document.getElementById('submit')
btn.addEventListener('click', e => {
// 阻止表单的默认提交
e.preventDefault()
const xhr = new XMLHttpRequest()
xhr.addEventListener('load', () => {
console.log(xhr.response);
})
xhr.open('post', 'https://www.imooc.com/api/http/search/suggest?words=js', true)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(`username=${username.value}&password=${password.value}`)
})
按下提交按钮, Ajax 发出请求,携带输入的数据,且不会跳转页面。
文本框按下回车自动触发表单提交:
一个表单下,如果只有一个文本框时,按下回车将会默认触发表单的提交事件。多个文本框时,按下回车不会触发表单的提交事件。
<form>
<input type='text'/>
</form>
解决方法:阻止表单的默认事件即可。
输入框宽度自动适应文本长度:
JS:
获取输入框中 value 值的字数,来动态设置 input 的宽度。
onchange:在属性值改变时还必须使得当前元素失去焦点才可以激活该事件。
onpropertychange: IE下,当一个HTML元素的属性改变的时候,都能通过 onpropertychange来即时捕获。在用js脚本改动该元素值时能触发onpropertychange事件。
oninput:是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器。但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。
<input type="text" style="width:50px;" id="test" onPropChanged ="handleChangeWidth()" oninput ="handleChangeWidth()"/>
<script type="text/javascript">
function handleChangeWidth() {
var dom = document.getElementById('test'),
textLength = document.getElementById('test').value.length;
//对字数及宽度做限制
if(textLength>20){
dom.style.width = '280px';
return false;
}
dom.style.width = textLength*14 + 'px';
}
</script>
CSS:
contenteditable 属性规定元素内容是否可编辑。可以结合 max-width、min-width 限制最大最小宽度。
去除获得焦点时蓝色的边框:outline:none;
<div contenteditable="true" style = 'width:300px'>这是一段可编辑的段落。请试着编辑该文</div>