簡體   English   中英

使用jQuery UI Slider調整圖像大小

[英]Resize an image using jQuery UI Slider

我正在使用jQuery UI滑塊按比例調整圖像大小,首先上傳圖像,然后傳遞到調整大小部分,到目前為止效果很好。 唯一的問題是,一旦我將范圍滑塊定位到圖像變小,其原始寬度!! 這是我的代碼:

//resize
var orginalWidth = $("#image").width();

$("#infoSlider").text(orginalWidth + ', 100%');

$("#slider").slider({
    value: 0,
    min: -50,
    max: 50,
    step: 10,
    slide: function (event, ui) {
        var fraction = (1 + ui.value / 100),
            newWidth = orginalWidth * fraction;

        $("#infoSlider").text('width :' + newWidth + ', Proportion :' + Math.floor(fraction * 100) + '%');

        $("#image").width(newWidth);
    }
});

// UPloded
$(function () {
            $(":file").change(function () {
                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = imageIsLoaded;
                    reader.readAsDataURL(this.files[0]);
                }
            });
        });

        function imageIsLoaded(e) {
            $("#slider").removeAttr("style")
            $('#image').attr('src', e.target.result);
        };

<div id="slider"></div>
<span id="infoSlider"></span>

<div class="target">
    <img id="image" src="#" alt="your image" />
    <input type='file' />
</div>   

請問我該如何解決! 非常感激
這是此問題的演示: DEMO問題: 在此處輸入圖片說明在此處輸入圖片說明

加載后,您需要在變量中獲取加載的圖像的大小。

添加:

orginalWidth = $("#image").width();

為了您的功能:

function imageIsLoaded(e) {
    $("#slider").removeAttr("style")
    $('#image').attr('src', e.target.result);
    orginalWidth = $("#image").width(); // store the loaded image size
};

檢查分數,寬度和比例的值。

當您將滑塊更改為減少時,它的外觀如下:

在此處輸入圖片說明

換回滑塊時,請注意圖像已恢復為原始大小

在此處輸入圖片說明

當您增加幻燈片時,請注意值會增加,圖像也會增加

在此處輸入圖片說明


編輯:

在選擇圖像之前使用滑塊以及選擇新圖像時,都會出現問題。 這是因為img標簽本身的寬度已更改,並且無論您選擇多大的圖像,它都將適合img標簽的新尺寸。

解:

使用動態添加的img標簽。 每次選擇新圖像時,都將刪除先前的img元素並添加一個新的img元素。 將新標簽的src分配給所選圖像。 這樣,每次選擇都會有效地重置圖像。

演示2: http//jsfiddle.net/XQSLk/5/

function imageIsLoaded(e) {
    var $newImg = $("<img>");                        // create a new img element
    $("#slider").removeAttr("style")
    $("#slider").slider('value', 0);                 // reset the slider
    $("#image").remove();                            // remove the existing img element
    $newImg.attr("id", "image");                     // add id to the new element
    $newImg.attr('src', e.target.result);            // assign src to new element
    $("#tgt").append($newImg);                       // add new element to DOM inside target div
    originalWidth = $("#image").width();             // now get the new width
    $("#infoSlider").text(originalWidth + ', 100%'); // reset the slider text
};

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM