想实现一个登录界面常用的效果:点击按钮后切换input框的显示/隐藏密码
首先想到的是,在按钮的点击事件里调用focus()使input获得焦点,代码如下:
<body><input id="psw" type="password"><button id="btn">显示/隐藏</button></body><script>var isExposed=false;var btn=document.getElementById('btn');var psw=document.getElementById('psw');btn.onclick=function(){psw.focus();if (isExposed) {//切换为隐藏psw.type='password';isExposed=false;}else{//切换为显示psw.type='text';isExposed=true;}}</script>
可这样做的效果是input失去焦点后又马上获得,效果不理想。
于是使用第二种方法,在按钮的onmousedown事件中阻止默认事件,代码如下:
<body><input id="psw" type="password"><button id="btn">显示/隐藏</button></body><script>var isExposed=false;var btn=document.getElementById('btn');var psw=document.getElementById('psw');btn.onclick=function(){if (isExposed) {//切换为隐藏psw.type='password';isExposed=false;}else{//切换为显示psw.type='text';isExposed=true;}}btn.onmousedown=function(e){//现代浏览器阻止默认事件if ( e && e.preventDefault ) e.preventDefault(); //IE阻止默认事件else window.event.returnValue = false; return false; }</script>
ok 成功实现效果~ :D