在函数中获得新的div值

时间:2019-07-05 17:22:13

标签: javascript file-upload parameters

我想在图像包装器中获取显示图像的宽度和高度,以对其进行处理。选中时会显示图像,因此包装纸的尺寸会发生变化。由于我需要包装的大小来做其他事情,因此将其用作参数。因此,更新图像后,我得到了旧图像包装器的高度和宽度。那么如何在显示新图像后如何修改代码以获取包装的新尺寸?

(我不需要有关提交或其他任何信息。这是代码的简化版本。)

<div style="width:300px">
        <div id="image-wrapper" style="border:2px dashed blue">
            <img src="text.jpeg" id="image" style="width:100%">
        </div>
        <p>width: <span id="x"></span></p>
        <p>height: <span id="y"></span></p>
    </div>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" id="user-file" accept="image/jpeg, image/jpg, image/png, image/gif" onchange="Image.display(this, document.getElementById('image'));Image.ready(document.getElementById('image-wrapper'),document.getElementById('x'),document.getElementById('y'))">
        <button type="submit">Submit
        </button>
    </form>
<script>
    class Image {
        static display ( event, target ) {
            if ( event.files[0] ) {
                let fileReader = new FileReader();
                fileReader.onload = function (event) {
                    target.setAttribute( 'src', event.target.result );
                }
                fileReader.readAsDataURL(event.files[0]);
            }
        }

        static ready (wrapper, x, y) {
            x.innerHTML = wrapper.clientWidth;
            y.innerHTML = wrapper.clientHeight;
        }
    }
</script>

2 个答案:

答案 0 :(得分:1)

已编辑:您必须等待图像加载,然后调用ready方法!

<div style="width:300px">
        <div id="image-wrapper" style="border:2px dashed blue">
            <img src="text.jpeg" id="image" style="width:100%" onload="Image.ready(document.getElementById('image-wrapper'),document.getElementById('x'),document.getElementById('y'))">
        </div>
        <p>width: <span id="x"></span></p>
        <p>height: <span id="y"></span></p>
    </div>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" id="user-file" accept="image/jpeg, image/jpg, image/png, image/gif" onchange="Image.display(this, document.getElementById('image'));">
        <button type="submit">Submit
        </button>
    </form>
<script>
    class Image {
        static display ( event, target ) {
            if ( event.files[0] ) {
                let fileReader = new FileReader();
                fileReader.onload = function (event) {
                    target.setAttribute( 'src', event.target.result );
                }
                fileReader.readAsDataURL(event.files[0]);
            }
        }

        static ready (wrapper, x, y) {
            x.innerHTML = wrapper.clientWidth;
            y.innerHTML = wrapper.clientHeight;
        }
    }
</script>

答案 1 :(得分:0)

尝试访问图像本身的widthclientWidthoffsetWidth属性,而不是包装器。