事件案例练习源码
JavaScript
1.密码显示与隐藏
仿京东显示密码:
点击按钮将密码框切换为文本框,并可以查看密码明文。
提示:
点击图片—要用到事件
变的是图片和文本框内容
要获取图片和input
改变图片 — src属性
改变 input框内容不可见====type属性
注意每点击一次变一次:
<body>
<style>
.box {
position: relative;
width: 400px;
border-bottom: 1px solid #ccc;
margin: 100px auto;
}
.box input {
width: 370px;
height: 30px;
border: 0;
outline: none;
}
.box img {
position: absolute;
top: 2px;
right: 2px;
width: 24px;
}
</style>
<div class="box">
<label for="">
<img src="img/close.png" alt="" id="eye">
</label>
<input type="password" name="" id="pwd">
</div>
<script>
var eye=document.getElementById("eye");
var pwd=document.getElementById("pwd");
var a=0;
eye.onclick=function()
{
if(a==0)//每点击一次就变化
{
pwd.type='text';
eye.src='img/open.png';
a=1;
}
else
{
pwd.type='password';
eye.src='img/close.png';
a=0;
}
}
</script>
</body>
2.淘宝点击关闭二维码
当鼠标点击二维码关闭按钮的时候,则关闭整个二维码。
提示:
点击x号,则会关闭二维码======要用到事件,获取图片
行内样式操作 display 属性可以隐藏元素 (display:none)
注意点击x号后 元素全部被隐藏
<body>
<style>
.box {
position: relative;
width: 74px;
height: 88px;
border: 1px solid #ccc;
margin: 100px auto;
font-size: 12px;
text-align: center;
color: #f40;
}
.box img {
width: 60px;
margin-top: 5px;
}
.close-btn {
position: absolute;
top: -1px;
left: -16px;
width: 14px;
height: 14px;
border: 1px solid #ccc;
line-height: 14px;
font-family: Arial, Helvetica, sans-serif;
cursor: pointer;
}
</style>
<div class="box">
淘宝二维码
<img src="img/tao.png" alt="" id="x">
<i class="close-btn">×</i>
</div>
<script>
var box=document.querySelector(".box");
var x=document.getElementById("x");
var i=document.querySelector('.close-btn');
var type=0;
i.onclick=function()
{
if(type==0)
{
box.style.display='none';
type=1;
}
else
{
box.style.display='block';
type=0;
}
}
</script>
</body>
3.排他思想
提示:如果有同一组元素,我们想要某一个元素实现某种样式, 需要用到 循环
所有元素全部清除样式(干掉其他人)
给当前元素设置样式 (留下自己)
注意顺序不能颠倒,首先干掉其他人,再设置自己
<body>
<button>锤地鼠</button>
<button>锤地鼠</button>
<button>锤地鼠</button>
<button>锤地鼠</button>
<button>锤地鼠</button>
<script>
var btn=document.getElementsByTagName('button');
for(var i=0;i<btn.length;i++)
{
btn[i].onclick=function()
{
for(var i=0;i<btn.length;i++)
{
btn[i].style.backgroundColor='';
}this.style.backgroundColor='pink';
}
}
</script>
</body>