显示上传的图像,并将其缩放以适合图像字段而不失真



我已经使用下面的脚本来显示上传的图像,而无需重新加载页面,并且它工作得很好。

除了缩放上传的图像以适合390px x 390px的img对象。

如果我可以将背景图像设置为上传的文件,css将很好地缩放图像,但目前的方法只是拉伸src图像以填充整个字段。

如何修改此函数以将e.target.result应用于背景图像而不是src?

//function to display selected image
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            //$('#optimageinput').attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}

你可以使用jQuery的.css():

reader.onload = function (e) {
    $('#optimageinput').css('background-image', 'url(' + e.target.result + ')');
};

最新更新