【问题标题】:Displaying an Image in Search Bar HTML在搜索栏 HTML 中显示图像
【发布时间】:2020-07-31 03:49:46
【问题描述】:

我正在整理这张表,并在其中添加了一个搜索功能。但是在搜索栏中,我想为背景图像放置一个搜索图标 png 文件,就像W3Schools 上的示例一样。我把它放在了 myInput 字段中,但是搜索栏中要么什么都没有出现,要么它太大了,以至于你可以看到搜索图标的一小块顶角,我不知道如何修复它。

#myInput {
  background-image: url('https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-512.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
<input type="text" id="myInput">

【问题讨论】:

  • 给我一秒钟,如果我想这样做,我必须从我的代码中删除一堆东西,因为我在一个文件中拥有所有 javascript/css/html 并且它从 info 填充表格来自共享点站点,因此无法在这里工作
  • 你可能需要调整背景位置,我也不认为这是一个跨浏览器的解决方案。你宁愿在前面加上一个元素祝你好运
  • @David 仅以此为例,这是我想要实现的目标,但我的表格要复杂得多w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table
  • 您确定图片网址正确吗?换句话说,如果你把它放在一个img标签中它会显示出来吗?
  • 不过,它与图像有关。如果我将您的图片 URL 替换为 W3Schools 示例,它不起作用。

标签: html css


【解决方案1】:

您需要使用background-size 属性。因为图像大于输入,所以您看到的是图片的白色部分。通过将属性设置为contain,图像会缩小到input 的大小。

#myInput {
  background-image: url('https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-512.png');
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 30px;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
<input placeholder="Search..." type="text" id="myInput">

注意:您还应该将 background-position 属性设置为 0 或将其全部删除;否则,搜索图标将向右下方倾斜。 如果您想让图标变小,请将 background-position 更改为 left center 并将 background-size 设置为您选择的 px 值。

【讨论】:

  • 几乎成功了...看看我最近编辑的图片
  • @zgoforth 这是因为你的background-position 仍然设置为10px,所以它向下和向右倾斜。将其设置为0px 0px,它将起作用。我将更新我的答案以包含此解释
  • 马文你是最棒的!谢谢
  • 您是否知道可以将图像缩小一点,使其与文本相比不会很大?
  • @zgoforth 不客气!如果我的回答对你有用,请务必点击对勾接受答案。
【解决方案2】:

HTML

<div class="fake-input">
    <input type="text" />
    <img src="http://www.zermatt-fun.ch/images/mastercard.jpg" width=25 />
</div>

CSS

.fake-input { position: relative; width:240px; }
.fake-input input { border:none; background-color:#fff; display:block; width: 100%; box-sizing: border-box }
.fake-input img { position: absolute; top: 2px; right: 5px }

Source is here

【讨论】:

  • 用户想要左边的图标,而不是右边的。另外,为什么这个类被命名为“fake-input”?
  • 他可以更新css,这只是一个开始的例子,fake-input是ust类名:)
猜你喜欢
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多