我如何把一个图标内的形式的输入元素?

现场版本:潮汐力主题


当前回答

在输入中定位图标的一个简单易行的方法是使用下面代码所示的CSS属性position。 注意:为了清晰起见,我简化了代码。

创建围绕输入和图标的容器。 将容器位置设置为相对位置 将图标设置为绝对位置。这将使图标相对于周围的容器进行定位。 使用顶部,左侧,底部,右侧来定位容器中的图标。 设置输入内的填充,使文本不与图标重叠。

#输入容器{ 位置:相对; } #输入容器> img { 位置:绝对的; 上图:12 px; 左:15 px; } #输入容器>输入{ padding-left: 40像素; } < div id = "输入容器" > < img / > <输入/ > < / div >

其他回答

只需使用CSS中的background属性即可。

<input id="foo" type="text" />

#foo
{
    background: url(/img/foo.png);
}

我用下面的代码实现了这一点。

首先,你弯曲容器,使输入和图标在同一行。对齐物品可以使它们处于同一水平线上。

然后,使输入占用宽度的100%。给出图标的绝对位置,使其与输入重叠。

然后为输入添加右填充,这样输入的文本就不会到达图标。最后使用css属性给图标留出一些距离输入框边缘的空间。

注意:Icon标签可以是一个真正的图标,如果你是在ReactJs中工作,也可以是一个占位符,用于你在项目中使用图标的任何其他方式。

.inputContainer { 显示:flex; 对齐项目:中心; 位置:相对; } .input { 宽度:100%; padding-right: 40像素; } .inputIcon { 位置:绝对的; 右:10 px; } < div class = " inputContainer”> <input class="input" /> <图标类="inputIcon" /> < / div >

我遇到过这样的情况。它没有工作,因为背景:#ebebeb;我想把背景放在输入字段,该属性不断地显示在背景图像的顶部,我无法看到图像!我把background属性移到background-image属性上面,它起作用了。

input[type='text'] {
    border: 0;
    background-image: url('../img/search.png');
    background-position: 9px 20px;
    background-repeat: no-repeat;
    text-align: center;
    padding: 14px;
    background: #ebebeb;
}

我的解决方案是:

input[type='text'] {
    border: 0;
    background: #ebebeb;
    background-image: url('../img/search.png');
    background-position: 9px 20px;
    background-repeat: no-repeat;
    text-align: center;
    padding: 14px;
}

值得一提的是,边框、填充和文本对齐属性对于解决方案并不重要。我只是复制了原始代码。

我不想改变我的输入文本的背景,也不会与我的SVG图标工作。

我所做的就是为图标添加负边距,这样它就会出现在输入框中

并在输入中添加相同的填充值,这样文本就不会出现在图标下面。

<div class="search-input-container">

  <input
    type="text"
    class="search-input"
    style="padding-right : 30px;"
  />

  <img 
    src="@/assets/search-icon.svg" 
    style="margin-left: -30px;"
   />

</div>

*内联风格是为了可读性考虑使用类

css后台解决方案做的大多数情况下,但它有一个问题与webkit (chrome)自动完成的图标消失。

还有其他解决方案,包括通过将输入包装在div中并添加一个额外的元素(img、div或类似元素)来更改html/dom结构。 我不喜欢解决方案,因为你需要调整元素css的绝对位置和/或调整像素大小,以获得正确的位置。 或者重新创建输入边框,将输入和img“合并”在一起。

所以这个解决方案是基于css背景图像不应用在输入元素,但应用在包装div。

HTML:

<div class="input-email">
    <input type="text" placeholder="Email" name="email" id="email">
</div>

CSS:

.input-email {
    background: url(/assets/images/email.svg) no-repeat scroll 14px 11px;
    display: inline-block;
} 

.input-email input{
    padding-left: 40px;
    background-color: transparent !important;
}

input:-webkit-autofill, input:-webkit-autofill:hover, 
input:-webkit-autofill:focus, input:-webkit-autofill:active {
    transition: background-color 5000s ease-in-out 0s;
}

这种方式与.input-email类我定义我的图标图像为div背景(不受webkit autocomplete背景的影响)。 我将input元素的左侧填充为图像提供空间,并将其设置为透明(当不应用自动完成时,这是有效的) 最后,在webkit-autofill类中,我删除了自动补全设置的背景色。

注意:在第2点我设置了transparent !important,因为-internal-autofill-selected会在浏览器中呈现,如果不设置我的also为!我就无法覆盖它。

input:-internal-autofill-selected {
    background-color: -internal-light-dark(rgb(232, 240, 254), rgba(70, 90, 126, 0.4)) !important;
}

我从这个帖子https://www.py4u.net/discuss/1069380得到了我的解决方案 我做了一些调整,虽然主要的功劳是他们。