目录
1、css代码
2、html代码
3、js代码
完整代码
效果图
1、css代码
.box{
width: 400px;
height: 300px;
margin: 100px auto;
position: relative;
}
input{
width: 250px;
height: 40px;
outline: none;
}
span{
display: block;
position: absolute;
min-width: 270px;
max-width: 400px;
/* width: 270px;
height: 40px; */
border: 1px solid red;
top: -50px;
word-wrap: break-word;
margin-bottom: 20px;
/* display: none; */
opacity: 0;
font-size: 18px;
line-height: 20px;
}
2、html代码
<div class="box">
<span></span>
<input type="text" placeholder="请输入您的快递单号">
</div>
3、js代码
<script>
// 需求:获取焦点出现框,并内容实时与input同步
const ipt=document.querySelector('input')
const span=document.querySelector('span')
//获取焦点,显示span
ipt.addEventListener('focus',function() {
// span.style.display='block'
if(ipt.value.trim()===''){
span.style.opacity=0
}else{
span.style.opacity=1
}
})
//span的内容等于input框内容
ipt.addEventListener('input',function() {
if(ipt.value.trim() ===''){
span.style.opacity=0
}else{
span.innerHTML=ipt.value
span.style.opacity=1
}
})
//失去焦点,隐藏span
ipt.addEventListener('blur',function(){
// span.style.display='none'
span.style.opacity=0
})
</script>
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 400px;
height: 300px;
margin: 100px auto;
position: relative;
}
input{
width: 250px;
height: 40px;
outline: none;
}
span{
display: block;
position: absolute;
min-width: 270px;
max-width: 400px;
/* width: 270px;
height: 40px; */
border: 1px solid red;
top: -50px;
word-wrap: break-word;
margin-bottom: 20px;
/* display: none; */
opacity: 0;
font-size: 18px;
line-height: 20px;
}
</style>
</head>
<body>
<div class="box">
<span></span>
<input type="text" placeholder="请输入您的快递单号">
</div>
<script>
// 需求:获取焦点出现框,并内容实时与input同步
const ipt=document.querySelector('input')
const span=document.querySelector('span')
//获取焦点,显示span
ipt.addEventListener('focus',function() {
// span.style.display='block'
if(ipt.value.trim()===''){
span.style.opacity=0
}else{
span.style.opacity=1
}
})
//span的内容等于input框内容
ipt.addEventListener('input',function() {
if(ipt.value.trim() ===''){
span.style.opacity=0
}else{
span.innerHTML=ipt.value
span.style.opacity=1
}
})
//失去焦点,隐藏span
ipt.addEventListener('blur',function(){
// span.style.display='none'
span.style.opacity=0
})
</script>
</body>
</html>