2012-10-10 26 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是按鈕,我只是將它定位在右側,並隱藏了邊框,使背景變得透明,並使光標在鼠標懸停時發生變化。