首页 文章

更改图像文件javascript的宽度

提问于
浏览
-1

如果用户选择图像我在div中将其预览为背景图像,我有2个输入字段(宽度,高度),因此用户可以确定上传图像的宽度和高度 .

如果用户更改宽度/高度,我想调整预览图像的大小 .

但我一直收到错误: Uncaught TypeError: Cannot read property 'width' of undefined

这是我的代码:

HTML - 输入字段

<input type="file" name="sourceImage" id="sourceImage">

    <input type="text" class="form-control input-width input-px" maxlength="2" name="width">CM breed
    <input type="text" class="form-control input-height input-px" maxlength="2" name="height">CM hoog

Javascript - 功能

在此功能中,我预览图像并将图像放入图像var

var image;

  $(function() {

      $("#sourceImage").on("change", function()
      {
          var files = !!this.files ? this.files : [];
          if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

          if (/^image/.test( files[0].type)){ // only image file
              var reader = new FileReader(); // instance of the FileReader
              reader.readAsDataURL(files[0]); // read the local file

              image = this.result;

              reader.onloadend = function(){ // set image data as background of div
                  $( ".source" ).css( "background-image", "url("+this.result+")" );
              }
          }
      });
  });

在这个函数中我想改变存储文件的图像var的宽度

$(function(){
      $(".input-px").on("change", function()
      {

          image.width($(".input-width").val());

      })
  })

1 回答

  • -1
    $(function(){
        $(".input-px").on("change", function() {
            var _width = parseInt($(".input-width").val(), 10) || 0;
            var _height = parseInt($(".input-height").val(), 10) || 0;
            if(_width > 0) {
                image.width(_width);
            }
            if(_height > 0) {
                image.width(_height);
            }
        });
    });
    

    编辑:请将此作为input-px onchange事件功能的增强功能 .

相关问题