我有以下文本框:
<input type="text" id="fromAdd" class="styledTB searchBDir" />
CSS:
.styledTB {
padding-left: 5px;
background: #E8E8E8;
opacity: 1;
border: none;
outline: none;
right: 35px;
box-shadow:
0px 5px #BBB,
0px 8px 10px rgba(148, 148, 148, 0.5);
}
.searchBDir {
height: 30px;
width: 90%;
}
显示:
如何在框右侧添加以下图标并使其可单击以获取地理位置:
要做这样的事情(我想调整图像大小以适合文本框而不是如图所示重叠):
我正在使用以下脚本,一旦单击图标并且用户授予权限,该脚本将填充文本框:
$.get("http://ipinfo.io", function (response) {
$("{textboxid}").text("Location: " + response.city + ", " + response.region);
}, "jsonp");
最佳答案
这就是我们正在做的事情
对 HTML 进行一些细微更改
<div class='styledTB'>
<input type="textbox" id="gpsInput" />
<button id="searchBDir"></button>
</div>
我们在这里所做的是为您的输入和按钮提供一些布局上下文。该容器将充当我们的边界框,用于布局其余元素。您可以仅使用输入来直观地完成此操作,但由于您有一个可点击的元素,因此将可点击区域设置为按钮是有意义的(为了可访问性、语义、等等等等……)。
CSS:
.styledTB {
position: relative;
display: inline-block;
height: 40px; /* Arbitrary number */
width: 400px; /* Arbitrary number */
}
.styledTB input {
width: 100%; /* Arbitrary number */
height: 100%;
padding-right: 40px;
box-sizing: border-box;
}
#searchBDir {
height: 100%;
width: 40px; /* Or however long you'd like your button to be, matches padding-right above */
background-image: url(/image/4v62r.png);
background-repeat: no-repeat;
background-position: 50% 50%;
border: none;
background-color: transparent;
position: absolute;
right: 0;
top: 0;
}
阅读评论,因为它们很有帮助,但作为高级概述:
我们将边界框(div)置于相对位置,以便我们可以绝对地对按钮进行排序。我们定义我们希望输入元素出现的大小(我任意选择了一些数字,无论您将它们设置为什么大小,它都应该类似地工作)并设置显示内联 block 以镜像正常的 input
元素。
然后我们强制盒子用 width
填充其容器。和height
被声明为 100%
并给盒子一个 padding-right
的40px
以匹配我们预期的按钮尺寸。我们设置box-sizing
至border-box
这样填充就不会强制输入大于其包含的框。这只是告诉浏览器考虑填充、边框和所有内部间距元素,以免增加元素的外部边界。
最后,我们将按钮设置为 position: absolute
并为其指定定位值以强制其位于框的右侧。我们为其提供 GPS 图标的背景图像,然后将其放置在按钮内的适当位置。
border
和background-color
规则可以覆盖默认浏览器将按钮渲染为凸起的灰色框。
希望对您有所帮助!
Fiddle here
关于html - 如何在文本框右侧添加图像并且文本不会溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26934222/