首先是案例展示:
实现过程,详细内容在代码中注释了.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<input id="a" type="text" />
<input id="b" type="text" />
<script>
// 获取两个input元素
var a = document.querySelector("#a");
var b = document.querySelector("#b");
var obj = {};
//input框输入过程中修改obj的name属性值,修改成鼠标抬起时所修改的那个值
document.onkeyup = function(e) {
obj.name = e.target.value;
};
//利用对象的defineProperty属性中的set方法将修改了的name属性值绑定到两个input框属性上
Object.defineProperty(obj, "name", {
set: function(e) {
b.value = e;
a.value = e;
}
});
</script>
</body>
</html>