这当然不是最优雅的解决方案,但我一直在努力寻找一种通过公开的 API 来实现它的方法......
我使用了第二个输入字段(最初隐藏在自动完成输入字段后面),然后在从自动完成列表中选择一个位置时将其带到前面(因此它隐藏了真正的自动完成)。这可以防止用户看到在文本框中填充的完整地址。有关演示,请参阅 this Fiddle。
HTML:
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text" onchange="hideAutocomplete()" />
<!-- Hidden field -->
<input id="autocompleteDummy" type="text" />
</div>
CSS:
#autocomplete,
#autocompleteDummy {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
#autocompleteDummy {
z-index: -1;
}
Javascript:
/*
* Function called when the value in the autocomplete textbox changes so it hides the real autocomplete and displays the 'fake' one
*/
function hideAutocomplete() {
// Populate the fake autocomplete with the text typed by the user - this prevents a blank box appearing
document.getElementById('autocompleteDummy').value = document.getElementById('autocomplete').value;
// Display the fake autocomplete
document.getElementById('autocompleteDummy').style.zIndex = 1;
// Hide the real autcomplete
document.getElementById('autocomplete').style.zIndex = -1;
}
您还需要修改您的 initAutocomplete() 函数以在填充地址字段后显示真正的自动完成功能。为此,请在方法结束之前和 for 循环之后添加以下行:
// Display the real autocomplete and hide the fake one
document.getElementById('autocomplete').style.zIndex = 1;
document.getElementById('autocompleteDummy').style.zIndex = -1;
我很想看看是否有人能提出更好的解决方案,因为这对我来说仍然有点“老套”。