2016-04-24 115 views
1

的右上角刪除按鈕我有,其中,選擇的圖像文件之後,示出了圖像預覽文件輸入,這裏是jQuery代碼如何顯示在圖像

<script> 
    var loadFile = function(event) { 
    var output = document.getElementById('output'); 
    output.src = URL.createObjectURL(event.target.files[0]); 
    }; 
</script> 

的Html代碼 - >

<input type="file" name="image_file" id="cretor" accept="image/*" onchange="loadFile(event)"> 
<img id="output" width="80" height="80"> 

以上代碼在選擇圖像後立即生成圖像預覽,但是如何顯示圖像右上角的刪除按鈕並重置文件輸入並刪除該圖像

這裏是我試過的在圖像的右上角顯示刪除按鈕

<div class="img-wrap"> 
    <button id="clear" onclick="twz()">x</a> 
    <img src="blob:https://www.example.com/c880bfa4-25d0-4e2b-91e4-d722b864cc79" id="output"> 
</div> 

CSS

.img-wrap { 
    position: relative; 

} 
.img-wrap .close { 
    position: absolute; 
    top: 2px; 
    right: 2px; 
    z-index: 100; 

} 

現在,我怎麼能生成按鈕,將其放置在右上角,因爲使用loadFile函數只生成圖像預覽

+0

快速觀察...

回答

2

有在您的代碼中有2個錯誤:

1-您沒有正確關閉您的button,所以正確的標記應該是:

<input type="file" name="image_file" id="cretor" accept="image/*"onchange="loadFile(event)"> 


<div class="img-wrap"> 
<button id="clear" class="hide" onclick="twz()">x</button> 
<img id="output" width="80" height="80"> 

2-二是在你的CSS您儘量選擇一個名爲close類,但標記有id="clear"這樣你就可以用這種方式改變你的CSS和將正常工作:

.img-wrap { 
position: relative; 
float:left; 
} 

.img-wrap #clear { 
position: absolute; 
top: 2px; 
right: 2px; 
z-index: 100; 

} 

.hide{ 
    display:none; 
} 

只有在選擇圖像時才能顯示按鈕,從按鈕中刪除類別hide。您的腳本變爲:

<script> 
var loadFile = function(event) { 
var output = document.getElementById('output'); 
output.src = URL.createObjectURL(event.target.files[0]); 
$("#clear").removeClass("hide"); 
}; 
</script> 
+0

我面臨的問題是預覽正在動態生成,因此刪除按鈕也應該動態生成 –

+0

您是否正在使用jQuery?你可以添加一個按鈕裏面的div ... – cesare

+0

是的,我使用的是jquery,所以我應該在img-wrap div中生成buuton? –