开发网站页面时,会遇到两个文本框内容联动的需求,在一个文本框中增加内容,删除内容,另一个文本框中的也随之跟着产生变化,那么,这个效果该如何实现呢,下面,济南网站建设小编就来为大家分享,通过编写JavaScript代码来解决这个需求的小案例,有需要的朋友可以过来参考一下。
关键代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>JavaScript文本框内容联动变化</title>
<style>
.wrap {
margin: 50px;
}
input {
width: 300px;
padding: 10px;
font-size: 16px;
border: 1px solid #999;
border-radius: 4px;
margin: 10px 0;
display: block;
}
</style>
</head>
<body>
<div class="wrap">
<input type="text" id="inp1" placeholder="在此输入内容">
<input type="text" id="inp2" placeholder="同步显示内容">
</div>
<script>
let inp1 = document.getElementById('inp1');
let inp2 = document.getElementById('inp2');
// 第一个框输入,第二个同步变化
inp1.oninput = function(){
inp2.value = this.value;
}
// 第二个框输入,第一个同步变化
inp2.oninput = function(){
inp1.value = this.value;
}
</script>
</body>
</html>
评论