DHTML: Get updated element size

眉间皱痕 提交于 2019-12-22 10:16:10

问题


I'm updating the src attribute of an <img> tag in javascript. After I've done this, I need to get the new height of its parent <div> so that I can update the size of other elements on the page. If I retrieve the parent's offsetHeight property directly after updating the image's src, however, I get the height before the change was made. Is there a way to force the browser to render the updated page so that I can get the new height?

Repro:

<html>
<head>
<script type="text/javascript">
    function changeImage(){
        document.getElementById("image").src = "b.jpg";
        // here I need to re-render the page
        alert(document.getElementById("parent").offsetHeight);
        // ^ alerts the height of a.jpg, not b.jpg (unless this is the second click)
    }
</script>
</head>

<body onclick="changeImage()">

<div id="parent">
    <img id="image" src="a.jpg" />
</div>

</body>
</html>

回答1:


You might need to wait for the image to finish loading before the height is available. In your sample code, setting the "src" attribute will load the image (b.jpg) asynchronously so you may want to attach an "onload" hander on that element to be notified when it's finished loading and rendering.




回答2:


If you don't need the new height right away, use Marc's solution. However, if you need the height right when the user clicks, you'll need to preload b.jpg. Then, I don't know if the height will be correct straight in the same function, but I suppose a setTimeout('alert(document.getElementById("parent").offsetHeight);',1); would alert the height within a millisecond.



来源:https://stackoverflow.com/questions/399508/dhtml-get-updated-element-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!