2012-10-10 28 views
0

任何人都可以给我看一个代码片断,它产生类似于这个例子中的“搜索框”:www.dx.com?如何将文本框内的图像?

让我吃惊的是,谷歌搜索“textfield inside image”只给了我所有“textfield里面的图片”的结果。

+2

将一个文本字段放在图像“内部”是无效的 - IMG元素*不能包含内容。但是,它可能是“分层以上”。拔出你最喜欢的DOM/CSS检查(IE开发工具,Firebug,无论Chrome有什么)等工具,并看看www.whatever.com是如何做到的:) – 2012-10-10 00:25:30

回答

4

你不能把图像等元素中,但你可以做以下的达到这个效果:

使用css为:

<style> 
    .search-container{background:url(your/image/path) no-repeat top left;width:200px;height:50px;} 
    .search-container input{width:150px;} 
    .search-container button{width:40px;} 
</style> 

而且html一样:

<html> 
    <head></head> 
    <body> 
     <div class="search-container"> 
      <input type="text" /> <button>Search</button> 
     </div> 
    </body> 
</html> 

现在,search-container将与一个背景图像和里面你可以把你的搜索形式(输入和按钮)。

,如果你想不“默认”风格的输入您可以重置:

.search-container input{border:none;background:transparent;} 
0

至于其他的答案中指出你要找的是无效的方法。您基本上将图像顶部的文本字段分层,并隐藏了字段的边框和背景,因此唯一可见的就是图像。

他们使用绝对定位来设置图像顶部的文本字段和按钮,删除边框和背景,使元素基本上不可见,从而显示图像背后的图像。这里有一个简单的例子。 http://jsfiddle.net/a2pQ2/2/

下面是HTML

<div class="searchbox"> 
    <input type="text" class="search" id="search" value="Search in 80,000+ Gadgets..."> 
    <button id="btnSearch" type="button" class="btn_search"></button> 
</div>​ 

和CSS

.searchbox { 
    position: relative; 
    width: 367px; 
    height: 36px; 
    background: url(http://tctel.com/search.jpg) no-repeat; 
} 
.searchbox .search 
{ 
    border: none; 
    position: absolute; 
    top: 6px; 
    left: 6px; 
    height: 24px; 
    line-height: 24px; 
    width: 287px; 
    outline: none; 
} 
.searchbox .btn_search 
{ 
    border: none; 
    position: absolute; 
    top: 2px; 
    right: 2px; 
    height: 32px; 
    width: 71px; 
    background: transparent; 
    cursor: pointer; 
}​ 

所以搜索框是容器,它有一个背景图像是367px宽和36px高。所以我们将其设置为相对位置,以便我们可以绝对定位孩子。

.search是文本字段。它被设置为绝对位置,并且我将它设置为从顶部到左边6px,以匹配图像的边界,因此出于同样的原因将高度设置为24。我隐藏了边界和轮廓。

.btn_search是按钮,我只是将它定位在右侧,并隐藏了边框,使背景变得透明,并使光标在鼠标悬停时发生变化。