需求场景:左边输入框输入内容,右边输入框用placeholder展示,当placeholder的内容宽度超过右边输入框的宽度时,placeholder强行替换为“请选择”
注意事项:1、左右输入框的大小、样式都无关;
2、实际业务中右边输入框的大小样式是随机的,所以示例代码中右边输入框加了左右不等的内边距,并且监听了浏览器窗口大小的变化,而具体的业务开发时右边输入框的大小是随机确定的,大小一般不会变化,所以无需监听浏览器窗口大小改变事件。
完整的示例代码:
<!DOCTYPE html>
<html lang="zh">
<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>
<style type="text/css">
input {
border: 1px solid gray;
width: 20%;
}
#input2{
padding-left: 10px;
padding-right: 2px;
width: 20%;
}
</style>
</head>
<body>
<input id='input1' type="text" name="title" oninput="onc()" />
<input id='input2' type="text" name="userInput">
<script>
function textSize(fontSize,fontFamily,text){
var span = document.createElement("span");
span.id = 'referenceSpan'
var result = {};
result.width = span.offsetWidth;
result.height = span.offsetHeight;
span.style.visibility = "hidden2";
span.style.fontSize = fontSize;
span.style.fontFamily = fontFamily;
span.style.display = "inline-block";
var isExists = document.getElementById("referenceSpan");
if (isExists) {
document.body.removeChild(isExists);
}
document.body.appendChild(span);
if(typeof span.textContent != "undefined"){
span.textContent = text;
}else{
span.innerText = text;
}
result.width = parseFloat(window.getComputedStyle(span).width) - result.width;
result.height = parseFloat(window.getComputedStyle(span).height) - result.height;
document.body.removeChild(span);
return result;
}
window.onc = function onchange(){
let input1 = document.getElementById('input1');
let input2 = document.getElementById('input2');
let placeholder = '请选择' + input1.value;
let cStyle = window.getComputedStyle(input2);
let size = textSize(cStyle.fontSize,cStyle.fontFamily, placeholder);
console.log(size.width, cStyle.width)
if (size.width > parseFloat(cStyle.width)) {
console.log("你输入的标题太长了",parseFloat(cStyle.width));
input2.placeholder = '请选择';
}else {
input2.placeholder = placeholder;
}
}
window.onresize = function(e){
window.onc();
}
</script>
</body>
</html>