添加到 div 的图像不受滚动条的影响

Images added to div are not affected by the scrollbar

我有一个带滚动条的空 div:

<div id="figure1" style="width:1000px; height:300px; overflow:scroll;"></div>

并使用 javascript 我将图像添加到 div:

function add_img(imgID, src, x, y, height, width){
    var img = document.createElement("img");
    img.setAttribute('id', imgID);
    img.setAttribute('src', src);
    img.style.left = x;
    img.style.top = y;
    img.style.width = width;
    img.style.height = height;
    img.style.position = 'absolute';
    document.getElementById('figure1').appendChild(img);
}

当我在 1000x300 像素框外添加新图像时,我希望该图像仅在您使用滚动条时可见。

相反,位于框外的图像超出了图 1 的边缘。滚动条没有任何作用。

如何防止图片溢出?

谢谢!

我看到两个问题 - 首先您需要将 + "px" 添加到您的尺寸(至少如果您像我一样使用整数类型参数)。

另一件事是不要使用 position = "absolute"。例如 position = "relative" 似乎可以解决问题。 (如果你愿意,可以进一步阅读 CSS 中的布局选项,祝你好运)

https://jsfiddle.net/xpsu9usw/