簡體   English   中英

我想使用jQuery在div中獲取並顯示圖像

[英]I want to fetch and show an image in a div using jQuery

我想在單擊“ 附加文件”按鈕( filebtn css類)時獲取圖像,並在div中顯示此圖像( upload-img css類)。

這是我的代碼:

<script>
    $('.file').change(function () { 
        $(this).next('.file_selected').val($(this).val()) });   
        $('.upload-img').hide();
        $('.fileinput').click(function(){
        $(this).parent().find('.upload-img').slideDown();
    });
</script>

<div class="fileinput form-control">
    <input type="file" id="" name="" class="file" />
    <input type="text" class="file_selected" value="Upload Related Photo" />
    <input type="button" class="filebtn" value="Attach File" />
</div>
<div class="upload-img"> 
    <img src="images/profile.jpg" alt="profile" />
</div>

<br />

<style>
    .fileinput { position:relative; cursor:pointer; overflow:hidden; z-index:1; padding:0; display:inline-block;}
    .fileinput input[type=file] { position:absolute; width:100%; height:100%; filter: alpha(opacity=0); opacity: 0; left:0; top:0; cursor:pointer; z-index:9; }
    .fileinput input[type=text] { background:none; border:none; }
    .filebtn { background:#aaaaaa; color:#fff; position:absolute; right:0; height:100%; top:0; padding:0 12px; cursor:pointer; border:0; text-transform:uppercase; font-size:14px;}
    .file_selected{height:37px; padding:6px 12px; width:78%;}
</style>

您可以在upload-img div中添加canvas元素。 我用的是jQuery。 這里的例子:

html代碼:

<input id="fileUploader" type="file" name="Files" onchange="fileUpload()" />
<div class="upload-img"> 
   <canvas class="image-preview" id="imageCanvas"></canvas>
</div>

CSS:

.image-preview {
    margin-top: 10px;
    height: 100px;
}

js代碼:

var canvas = $("#imageCanvas")[0];
var fileInput = $("#fileUploader")[0];
var imgHeight = 200;
function fileUpload () {
        var ctx = canvas.getContext('2d');
        var reader = new FileReader();
        reader.onload = function (event) {
            var img = new Image();
            img.onload = function () {
                var height, width;

                if (imgHeight) {
                    height = imgHeight;
                    var zoom = imgHeight / img.height;
                    width = img.width * zoom;
                } else {
                    height = img.height;
                    width = img.width;
                }

                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(fileInput.files[0]);
    }

暫無
暫無

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

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