2011-08-24 80 views
1

我想實現一個簡單的jquery函數,它基本上需要一個HTML鏈接並顯示圖像預覽,但我似乎無法得到它的工作。獲取圖像預覽jQuery

我用的jsfiddle - http://jsfiddle.net/W69aA/1/ - 顯示我想要做的代碼

$('.test').blur(function() { 

    var src = jQuery(this).val(); 
    var prevImg = jQuery('#prev > [id^="prevMe-"]').length; 

    if (src == null || src == undefined) { 
     //trying to remove image if it's the same value or input is emptied 
     jQuery('#prevMe-' + (prevImg - 1)).remove(); 
    } else { 
     jQuery('#prev').append('<img id="prevMe-' + prevImg + '" style="max-width:50px;" src="' + src + '">'); 
    } 
}); 

我想:

  1. 刪除預覽圖像如果輸入鏈接被刪除
  2. 如果輸入有顯示預覽圖像
  3. 驗證是圖像[gif,jpg,png]

任何人都可以協助嗎?

回答

1

你實現共同合作的一個點的圖像,我已經試着改變它做更多你想要的東西。希望能幫助到你。

http://jsfiddle.net/W69aA/10/

<script> 
$('.test').blur(function() { 

var src = jQuery(this).val(); 
var LinkedImage = $(this).data('linkedImage'); 
$(LinkedImage).remove(); 

if(!src.match("http:\/\/.*\/(.*)\.(jpg|jpeg|png|gif)") && src != "") 
{ 
    $("#warning").html("Must be an image"); 
     return false; 
} else { 
    $("#warning").html(""); 
} 

if (src != "") { 
    $('#prev').append('<img class="previewImage" style="max-width:50px;" src="' + src + '">'); 
    $(this).data('linkedImage', $('img:last' ,'#prev'));  
} 

}); 
</script> 

<input id="0" type="text" class="test" /> 
<input id="1" type="text" class="test"/> 
<input id="3" type="text" class="test"/> 

<div id="warning"></div> 
<div id="prev"></div> 
+0

非常感謝:)我認爲.match()可能會更好,如果它匹配(/ http:\/\/\ S +(\。png | \ .jpg | \ .gif)/ g); '?此外,試圖找出它 - 但圖像預覽似乎出現 - 控制檯顯示錯誤「資源解釋爲圖像,但與MIME類型應用程序/ json.' [在Chrome] – Tom

+0

傳輸即,因爲這對我來說[http: /educ661-373wikiarticle.wikispaces.com/file/view/test.jpg/149584695/test.jpg]?另外,如果我刪除輸入鏈接 - 預覽仍然存在? – Tom

+0

我來看看。我正在使用Firefox,沒想到要嘗試其他任何事情。 – Henry

0

您可能想要更改的第一件事是在驗證輸入值時添加src == ""以檢查空字符串。

if (src == null || src == undefined) { 

看看這個fiddle您可以驗證它是否使用這個正則表達式

if(!src.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$")) 
    { 
     alert("must be an image") 
     return false; 
    } 

你的最終代碼會是這個樣子

$('.test').blur(function() { 

    var src = jQuery(this).val(); 

    if(!src.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$")) 
    { 
     alert("must be an image") 
     return false; 
    } 

    var prevImg = jQuery('#prev > [id^="prevMe-"]').length; 

    if (src == null || src == undefined || src == "") { 
     //trying to remove image if it's the same value or input is emptied 
     jQuery('#prevMe-' + (prevImg - 1)).remove(); 
    } else { 
     jQuery('#prev').append('<img id="prevMe-' + prevImg + '" style="max-width:50px;" src="' + src + '">'); 
    } 
}); 
+0

非常感謝您試用:)我確實嘗試了圖像[即嘗試 - http://educ661-373wikiarticle.wikispaces.com/file/view/test.jpg/149584695/test.jpg),它不斷給我一個錯誤?如果鏈接從輸入中刪除,它也不會刪除prev-image? – Tom

0

我想你忘記了一點點複雜的問題: 如何獲得真正的ImagePath?如果您想在不上載圖像的情況下創建真實預覽,則需要它。
我解決了這個問題並浪費了很多時間,因爲從javascript獲取路徑幾乎是不可能的。但最終找到了一個獲得真正預覽的方法。
我會在這裏分享它,因爲您的代碼提供了足夠的驗證。所以我可以支持它完成。
當選擇圖像時,使用文件mannager或客戶端的exporer創建臨時路徑,並且它是可訪問的。因此,您必須使用方法:「URL.createObjectURL()」從該路徑創建一個對象,然後將其附加到元素的「src」屬性。 這裏是一個代碼片段作爲樣本:

1. a small styles sheet to easy encode 
// myStyles.css 
// ... 
.collapsed-element { diplay: none; } 
// ... 
2. A hidden container element to prepare the previewed image 
<!-- my html page !--> 
<!-- the workhorse in a hidden container --> 
<div id="canvas-container" class="collapsed-element"> 
    <img src="" class="canvas" id="canvas-input"> 
</div><div class="clear-block"></div> 

3. The widget to have a working input set 
<!-- The imput set: a table-row with a file input and a related img-preview element --> 
<table id="my-image-getter-widget"> 
<tr> 
<td style="width: 15%" id="prw-container"> 
    <!-- fibopad.gif is a transparent pad using Fibonacci numbers as dimentions (a personal preference) --> 
    <!-- graphema will be the file input name; so I asign it as a class-prefix attribute in the related viewer --> 
    <img src="/path_to_a_transparent_image_pad/fibopad.gif" alt="" title="" width="46" height="75" class="graphema-vwr"/> 
</td> 
<td id="the-input-set-column" style="width: 85%"> 
     <!-- a text input to show the old path if you are editing and have an older loaded image --> 
     <!-- note the "graphema" word used elsewhere to relate elements and get a way to easy encode --> 
     <div class="container-inline"> 
      <div class="form-item" id="edit-graphema-txt-wrapper"> 
       <label for="edit-graphema-txt">Image File:</label> 
       <input type="text" maxlength="255" name="graphema_txt" id="edit-graphema-txt" size="45" value="" class="form-text"/> 
      </div> 
     </div> 
    <!-- The image input note the name="files[graphema]" attribute as array item --> 
    <!-- the class "enabled-prvw" will be added to inputs at onload event and will be used by javascript code to bind behaviors and get the preview --> 
     <div class="container-inline"> 
      <div class="form-item" id="edit-graphema-wrapper"> 
       <label for="edit-graphema">Load a image:</label> 
       <input type="file" name="files[graphema]" class="form-file" id="edit-graphema" size="60"/> 
      </div> 
     </div> 
    <!-- A helper tip for users --> 
    <div class="description"> 
      <br/>Blah, blah ... blah ... 
    </div> 
</td> 
</tr> 
</table><!-- widget end --> 

4. Finaly! the javascript 
// Filename: myimage-preview.js 
// a function to properly hall the preview image with a good container's resizing 
function set_dimentions_for_previewer(curwidth, curheight, standarlimit, targetid){ 
    var nw = standarlimit; 
    if(curheight > 10){ nw = parseInt((curwidth * standarlimit)/curheight); } 
    $(targetid).attr('height', standarlimit); $(targetid).attr('width', nw); 
} 

// a function to bind events and show selections (do not performs validation, so you must add it) 
// I'd commented my debug lines cause my modal dialog is not present 
function enable_preview_for_imageinput(){ 
    // var ondebug = Settings.lgq_debug_js_enabled; 
    $("input:file").each(function(){ 
    var id = '' + $(this).attr('id'); 
    var idselector = '#'+id;  
    // if(ondebug === 1){ estatus_add('binded change event<br>'); } 
    if(!$(idselector).hasClass('enabled-prvw')){ 
     $(idselector).bind("change", function(event){ 
      var chunk = id.split('-', 2); 
      var imgclass = '.'+chunk[1]+'-vwr'; 
      // /* 
      $('img.canvas').bind('load', function(){ 
       // if(ondebug === 1){ status_add('Image added to canvas <br>'); } 
       var curheight = $('img.canvas').attr('height'), curwidth = $('img.canvas').attr('width'); 
       // if(ondebug === 1){ status_add('dimentions width ='+curwidth+', height ='+curheight+' <br>'); } 
       set_dimentions_for_previewer(curwidth, curheight, 75, imgclass); 
       $('img.canvas').unbind('load'); 
      }); 
      $('.canvas').attr('src',URL.createObjectURL(event.target.files[0]));   
      $(imgclass).fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0])); 
      // var tit = 'Change event at '+id; 
      // var msg = ''+$(idselector).val();   
      // message_sys(tit, msg); 
     }); 
     $(idselector).addClass('enabled-prvw') 
    } 
    // if(ondebug === 1){ estatus_add('Binded input: '+id+' \n'); } 
    }); 
    // if(ondebug === 1){ message_sys('Load success', get_status()); } 
} 

// an onload call to enable all 
$(document).ready(function(){ 
    enable_preview_for_imageinput(); 
});