前端JS一些小案例
1.搜索栏内默认填充内容,但是鼠标点击搜索框后默认内容消失
用获取焦点的事件来写,聚焦后让标签的默认值变为空即可
拓展,默认填充的内容随机分配,根据用户的大数据的前十个浏览属性匹配相对应的商品名称
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="">
查找你喜爱的商品 :<input type="text" id="d1" value="显卡RTX4090" placeholder="">
</form>
<script>
let inputEle = document.getElementById('d1')// 锁定标签
inputEle.onfocus = function (){ //绑定事件
inputEle.value = '' // 被用户聚焦了,默认值改为空
}
inputEle.onblur = function (){ // 用户点击别的了,默认值 填上
inputEle.value = '下次再来哦'
}
</script>
</body>
</html>
2.前端校验用户名和密码部分规范
比如,设置前端页面的获取用户输入账号和密码时,不能提交空
如果有空,在输入框的右边提醒红色小字,然后如果用户又重新鼠标聚焦到输入框内,把右边红色小字消失掉
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>账号:
<input type="text" id="username">
<span class="errors" style="font-size:10px;color: rgba(220,20,60,0.76)"></span>
</p>
<p>密码:
<input type="password" id="password">
<span class="errors" style=" font-size:10px;color:rgba(220,20,60,0.76) "></span>
</p>
<button id="btn">提交</button>
<script>
//锁定储存按钮标签
let btnEle = document.getElementById('btn')
// 绑定事件
btnEle.onclick = function (){
// 锁定并储存用户输入的标签并拿到数据
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
//判断用户输入是否为空
if (username.length ===0){
//锁定并存储 输入框 提示标签
let span1Ele = document.getElementsByClassName('errors')[0]
//载入提示
span1Ele.innerText = '账号不能为空'
}
if (password.length ===0){
let span2Ele = document.getElementsByClassName('errors')[1]
span2Ele.innerText = '密码不能为空'
}
}
function func1() {
let inputNameEle = document.getElementById('username')
inputNameEle.onfocus = function () {
let span1Ele = document.getElementsByClassName('errors')[0]
span1Ele.innerText = ''
}
let inputPwdEle = document.getElementById('password')
inputPwdEle.onfocus = function () {
let span1Ele = document.getElementsByClassName('errors')[1]
span1Ele.innerText = ''
}
}
setTimeout(func1,1000)
</script>
</body>
</html>
标签:function,span1Ele,看看,前端,inputEle,案例,getElementById,let,document
From: https://www.cnblogs.com/wznn125ml/p/16960683.html