【问题标题】:How to check width and height from all images has been called by jquery?jquery调用了如何检查所有图像的宽度和高度?
【发布时间】:2017-03-03 06:51:39
【问题描述】:

我在 jquery 图像上遇到问题,我需要验证所有图像已被单击或使用 jquery 显示

这是我的代码,我如何添加新图像并显示图像

<script>
true_image = false;
var _URL = window.URL || window.webkitURL;
$(document).ready(function(){

    var abc = 0;
    var wrapper         = $(".images");
    var add_button      = $("#add_more");

    var x = 1;
    $(add_button).click(function(){

        x++;
            $(wrapper).append('<div class="col-md-4"><input id="file_input" class="images_file" type="file" name="file[]"/><img src="<?=base_url('/asset/images/BG/close.png')?>" class="remove_field" id="remove_image'+x+'"></img><div>');
    });

    $(wrapper).on("click",".remove_field", function(e){
        e.preventDefault(); $(this).parent('div').remove(); x--;
    });



    $('body').on('change', '#file_input', function() {
        var image ;
        if (this.files && this.files[0]) {
            image = new Image;
            image.onload =function() {
                console.log("width : "+this.width+" height: "+this.height);
                if(this.width < 700 || this.height < 650){
                    alert("The image width is " +this.width + " and image height is " + this.height +", minimum image width is 700 pixel and height is 650 pixel");
                    $("#submit").prop("disabled",true);
                }else{
                    $("#submit").prop("disabled",false);
                }
            };
            image.src = _URL.createObjectURL(this.files[0]);
            if(true_image == true){
                abc += 1;
                var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).after("<div id='abcd" + abc + "' class='abcd'></div><img class='images_view'  width='300' height='200' id='previewimg" + abc + "' src=''/>");
                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);
                $(this).hide();
                $("#abcd" + abc).append($("<img/>", {
                    id: 'img',
                    src: '<?=base_url('asset/images/BG/close.png')?>',
                    alt: 'delete'
                }).click(function() {
                    $(this).parent().parent().remove();

                    if(($('#file_input').val()) == undefined){
                        $(wrapper).append('<div class="col-md-4"><input id="file_input" class="images_file" type="file" name="file[]"/><div>');
                    }
                }));
            }

        }

    });

    function imageIsLoaded(e) {

        $('#previewimg' + abc).attr('src', e.target.result);


        $('.remove_field').hide();
    };

    $('body').on('click', '.images_view', function() {
        abc += 1;
        var cover = false;
        var image_id = this.id;
        $('.images_view').filter(function( index ) {
            if($( this ).attr( "id" ) === image_id){
                $(this).parent().find('#file_input').attr('name','cover');
                $(this).parent().find('#cover').remove();
                $(this).parent().append("<span class='cover' id='cover'>Cover</span>");
            }else{
                $(this).parent().find('#file_input').attr('name','file[]');
                $(this).parent().find('#cover').remove();

            }
        })

    });
});
</script>

从上面的代码中,我尝试上传多张图片,所以我添加了一个按钮,点击它后将添加一个新的&lt;input id="file_input" class="images_file" type="file" name="file[]"/&gt;,而不是在选择图片后它可以显示图片。我想尝试验证文件是图像文件,图像上的宽度和高度

我的问题是,如果我选择了错误图像(不在标准中),则按钮将被禁用,但如果在下一次选择中,我选择真实图像,则按钮恢复正常。我知道这会发生,因为我不检查之前选择的旧图像,这是我的问题,我不知道如何检查。

大家能帮我解决一下这个问题吗?

【问题讨论】:

  • 你能在sn-p中添加你的代码吗?
  • 您提供的代码不再叫sn-p,因为它太长了。尝试将您的逻辑分解成更小的部分并提供所需的部分。
  • 可能需要一些html代码

标签: javascript jquery html image


【解决方案1】:

这里有很多错误:)

首先;

var add_button      = $("#add_more");

var x = 1;
$(add_button).click(function(){ 

你应该这样做(add_button 已经被分配为 jQuery 对象):

add_button.click(function(){ 

当您单击 add_button 时,您会插入许多具有相同 id 的文件输入:

$(wrapper).append('<div class="col-md-4"><input id="file_input" class="images_file" type="file" name="file[]"/><img src="<?=base_url('/asset/images/BG/close.png')?>" class="remove_field"></img><div>');

并且您通过在此处分配来调用许多输入:

$('body').on('change', '#file_input', function() {

所以它会为相同的 id 触发多次。如果在单个输入中选择了多个文件,它也不会正常工作,因为您只在这里检查第一个:

if (this.files && this.files[0]) {

正如 cmets 中提到的,你应该分解这段代码,在我的建议中你应该从头开始编写它..

【讨论】:

  • 对不起,如果我的代码对您来说不太清楚,但在您上面提到的部分我没有看到我的项目中的任何错误,我通常可以输入多个图像,显示图像,我可以删除 javascript 中选择要删除的图像的图像
  • 也许在 jsfiddle 中重新创建场景会更容易看到发生了什么......可能还有其他一些 js 代码......
【解决方案2】:

首先我想说对不起,因为我的代码不清楚。

我得到了我的问题的答案,一些代码将被更改,并且将添加新代码

我使用 JavaScript localStorage 保存图像数据,以便检查最后加载的图像。

这是我使用localStorage检查图像的方法

    function check_image() {
        var images_log = JSON.parse(localStorage.getItem("images"));
        var type_reg = /^image\/(jpg|png|jpeg)$/;
        if(images_log != ""){
            for(var i=0;i<images_log.length;i++) {
                if(images_log[i]['type'] != undefined){
                    if(!type_reg.test(images_log[i]['type'])){
                        $("#submit").prop("disabled", true);
                        break;
                    }else{
                        $("#submit").prop("disabled", false);
                    }
                }
                if (images_log[i]['width'] < 700 && images_log[i]['height'] < 650) {
                    $("#submit").prop("disabled", true);
                    break;
                }else{
                    $("#submit").prop("disabled", false);
                }
            }
        }else{
            $("#submit").prop("disabled", false);
        }
    }

对于我写的所有有问题的代码,我将逐个解释。

<script>
    var _URL = window.URL || window.webkitURL;
    $(document).ready(function(){
        localStorage.clear();

        var abc = 0;
        var wrapper = $(".images");
        var add_button = $("#add_more");

        var x = 1;
        $(add_button).click(function(){
            x++;
            $(wrapper).append('<div class="col-md-4"><input id="file_input" class="images_file" type="file" name="file[]"/><img src="<?=base_url('/asset/images/BG/close.png')?>" class="remove_field" id="remove_image'+x+'"></img><div>');
        }); //added a new input file and delete button

        $(wrapper).on("click",".remove_field", function(e){
            e.preventDefault(); $(this).parent('div').remove(); x--;
            if(($('#file_input').val()) == undefined){
                $(wrapper).append('<div class="col-md-4"><input id="file_input" class="images_file" type="file" name="file[]"/><div>');
            }
        }); //if the delete button clicked, it will remove the input and the delete button

从那部分我为新的input file 做了一个简单的按钮,当它点击一个新的&lt;input type="file"&gt; 时,将添加一个新的按钮来删除&lt;input type="file"&gt;

这部分是如何调用图像加载,并为图像添加新的div。

    $('body').on('change', '#file_input', function() {
        var image = new Image ;
        if (this.files && this.files[0]) {

            //i add new var to check the file type
            var type = this.files[0].type; // received the type of the file;
            var type_reg = /^image\/(jpg|png|jpeg)$/; //for validate the file type


            abc += 1; 
            //this var already loaded in top of script which for sign the image delete button id, and the images id

            $(this).after("<div id='delete_image" + abc + "' class='delete_image'></div><img class='images_view'  width='300' height='200' id='previewimg" + abc + "' src=''/>"); 
            //add a new div class for the images.

            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
            $(this).hide();
            // for showing the images by call imageIsLoaded function, and hide the <input type="file">

这部分是用于删除图片,如果点击delete_image id 将删除图片,&lt;input type="file"&gt; 将删除localStorage 中的images_id;

            $("#delete_image" + abc).append($("<img/>", {
                id: 'img',
                src: '<?=base_url('asset/images/BG/close.png')?>',
                alt: 'delete'
            }).click(function() {
                var preview_id = $(this).parent().parent().find('.images_view').attr('id');
                var images_log = JSON.parse(localStorage.getItem("images"));
                if(images_log != "null" || images_log != null || images_log.length != 0){
                    for (i=0;i<images_log.length;i++){
                        if(preview_id == images_log[i]['id']){
                            images_log.splice(i,1)
                        }

                    }
                }
                localStorage["images"] = JSON.stringify(images_log);
                $(this).parent().parent().remove();

                if(($('#file_input').val()) == undefined){
                    $(wrapper).append('<div class="col-md-4"><input id="file_input"  class="images_file" type="file" name="file[]"/><div>');
                }
                check_image();
            }));

这里是为了验证。

      //here i changed my code how i disabled the button from on this to call a check_image() function and start using localStorage 

      if (type_reg.test(type)) { //check the file is an images file with jpg, png and jpeg

          image.onload = function() {

              //get the last localstorage and added it if a new images

              var images_arr = localStorage.getItem("images");
              var obj = [];
              if(images_arr){
                  obj= JSON.parse(images_arr);
              }
              obj.push({"id":  "previewimg" + abc,  'width' : this.width,'height' : this.height});
              localStorage.setItem("images",JSON.stringify(obj));

              //checked the image height and width showing the alert, and call the check_image() function

              if(this.width < 700 && this.height < 650){
                   alert("The image width is " +this.width + " and image height is " + this.height +", minimum image width is 700 pixel and height is 650 pixel, Please use another image!");

                   check_image();
              }else{
                  check_image();
              }
          };
      } else {
          alert('This file type is unsupported.');
          var images_arr = localStorage.getItem("images");
          var obj = [];
          if(images_arr){
              obj= JSON.parse(images_arr);
          }
          obj.push({"id":  "previewimg" + abc,  'type' : this.files[0].type});
          localStorage.setItem("images",JSON.stringify(obj));
          check_image();
      }


            image.src = _URL.createObjectURL(this.files[0]);
        }

    }); //end for ('body').on('change', '#file_input', function()

用于加载图像:

    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result).parent().find('.remove_field').remove();
    }

这就是我上传多张图片的全部方式,在上传之前显示图片并验证文件。

对不起,如果这段代码太长,因为我第一次写的代码不太清楚,所以我在这里解释一下我的代码是如何工作的

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2018-06-10
    • 2012-04-04
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多