2014-04-06 2 views
1

저는 매우 기본적인 Javascript/jQuery 작업에 대한 내 머리를 감싸려고 노력해 왔습니다.이미지 업 로더를위한 기본 jQueryUI 함수

나는 다음과 같은 HTML을 기본 이미지 업 로더를했습니다

다음 jQueryUI 플러그인에서, 이것은 내가 지금까지 가지고 코드입니다

div class="button one"></div> 
    <div class="button two"></div> 

    <div class="size ui-widget-content"> 
     <img src="" alt="" /> 
     <input type='file' name='userFile'> 
    </div> 

    <div class="button three"></div> 

: 내가 원하는 무엇

$(".size").resizable({ 
    grid: [60, 24], 
    ghost: true, 
    aspectRatio: //ratio function here , 
    stop: function(event , ui) { 
     var height = $(".size").css("height"); 
     var width = $(".size").css("width"); 
     $(".size img").css({ width : width, height: height }) 

    } 
}); 

$(".size > input").change(function() { 
    var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, ''); 
    var height = $(".size").css("height"); 
    var width = $(".size").css("width"); 

    $(".size img").css({ width : width, height: height }); 
    $(".size img").attr("src" , filename); 
    $(".size img").attr("alt", filename); 

    $(".three").show(); 

    var fr = new FileReader; 
    fr.onload = function() { // file is loaded 
     var img = new Image; 
     img.onload = function() { 
      var maxWidth = 960; 
      var maxHeight = maxWidth * (img.height/img.width); 
      $(".size, .size img").css({ width : img.width, height: img.height, "max-height": maxHeight , "max-width": maxWidth}); 
     }; 
    img.src = fr.result; // is the data URL because called with readAsDataURL 
    }; 
    fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating 
}); 

할 일은 다음과 같습니다. 내 하드 드라이브의 이미지를 페이지에 업로드하려고합니다.

지금까지 그렇게 좋았습니다.

이미지의 크기를 조정할 수 있도록 jQueryUI Resizable 함수를 사용했습니다. 이것은 완벽하게 작동합니다.

그러나 문제는 크기 조정 기능에 올바른 이미지 비율을 얻는 방법을 모른다는 것입니다. 크기를 조정할 때 내 이미지가 원래의 종횡비를 유지할 수 있도록이 함수가 필요합니다.

는 기본적으로,

모든 아이디어를 어떻게에서 $ ("크기는> 입력")를 $의 aspectRatio 속성에 .change 기능 ("크기는") .resizable 함수에서 값을 얻을 필요 이것을하기 위해?

---------------------- EDIT ----------------------- ------------------------

@ Frédéric Hamidi의 솔루션을 사용해 보았지만 제대로 작동하지 않았습니다. 나는에 코드를 편집 해했습니다 중 하나

$(".size").resizable("option", "start", function(event , ui){ 
     $(".size").resizable("option", "aspectRatio", 3/4); 
}); 

하지만이 나던 작품. Firebug 콘솔은 다음과 같이 말합니다 :

캐치 오류 : 초기화하기 전에 크기 재조정 할 수있는 메서드를 호출 할 수 없습니다. 위젯이 초기화 된 후에는 위젯의 option() 방법의 세터 양식을 통해, 당신의 change 처리기에서 aspectRatio 속성을 설정할 수 있습니다 방법 '옵션'

답변

1

전화를 시도했다.

$(".size > input").change(function() { 

    // Your current code... 

    $(this).parent().resizable("option", "aspectRatio", yourComputedAspectRatio); 
}); 
+0

시도했지만 작동하지 않았습니다. 비록 aspectRatio를 3/4으로 하드 코딩 했더라도 aspectRatio가 설정되지 않았습니다. – Brannie19

+2

이것이 정말 오래된 것입니다.하지만이 JQueryUI 버그가 수정되면이 _will_가 올바른 대답이 될 것입니다. https : //bugs.jqueryui .com/ticket/4186 그것은 8 년 동안 분명히 있었지만 다음 버전에서 실제로 수정 될 수있는 것처럼 보입니다 1.12.2 –