2011-08-24 7 views
1

기본적으로 HTML 링크를 사용하고 이미지 미리보기를 표시하는 간단한 jquery 기능을 구현하려하지만 작동하지 않는 것 같습니다.이미지 가져 오기 미리보기 jQuery

나는 JSFiddle 사용했다 - 내가하려고

$('.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 + '">'); 
    } 
}); 

코드와 함께 할 노력하고있어 보여 - http://jsfiddle.net/W69aA/1/을 : 입력 링크가 제거되면 미리보기 이미지를 제거

  1. 입력
  2. 검증이 이미지는 [GIF, JPG, PNG]가있을 경우
  3. 미리보기 이미지를 표시

누구든지 도와 줄 수 있습니까?

답변

1

같이 보일 것이 정규식을 사용하여 이미지의 경우이 fiddle 밖으로

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

확인 당신이 확인할 수 있습니다 , 나는 당신이 원하는 바를 조금 더 바꾸기 위해 바꿨습니다. 희망이 도움이됩니다. 어떻게 실제의 ImagePath를 얻을 :

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 유형 application/json으로 전송되었습니다.'오류가 표시됩니다. [Chrome에서] – Tom

+0

즉 [ /educ661-373wikiarticle.wikispaces.com/file/view/test.jpg/149584695/test.jpg]? 또한 입력 링크를 제거하면 미리보기가 유지됩니까? – Tom

+0

제가 보겠습니다.파이어 폭스를 사용하고 있었는데, 다른 것을 시도하려고 생각하지 않았습니다. – Henry

0

가장 먼저 변경하려는 것은 입력 값의 유효성을 검사 할 때 src == ""을 추가하여 빈 문자열을 확인하는 것입니다. 이

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

감사합니다. try - http://educ661-373wikiarticle.wikispaces.com/file/view/test.jpg/149584695/test.jpg) 오류가 계속 발생합니까? 또한 링크가 입력에서 제거되면 이전 이미지를 제거하지 않습니다? – Tom

0

난 당신이 조금 복잡한 문제를 잊고 생각? 이미지를 업로드하지 않고 실제 미리보기를 만들고 싶다면이 기능이 필요합니다.
저는이 문제를 해결하고 많은 시간을 낭비합니다. 자바 스크립트에서 경로를 얻는 것이 거의 불가능합니다. 그러나 마지막으로 실제 미리보기를 얻을 수있는 방법을 찾았습니다.
코드에서 충분히 유효성을 검사하므로 코드를 여기에서 공유 할 것입니다. 그래서 끝났습니다.
클라이언트 쪽에서 파일 관리자 나 exporer를 사용하여 이미지를 선택하면 임시 경로가 생성되어 액세스 할 수 있습니다. 따라서 "URL.createObjectURL()"메서드를 사용하여 해당 경로에서 객체를 만든 다음 < img/> 요소의 "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(); 
}); 
관련 문제