首页 > 解决方案 > 如何调整图像大小以适应按钮按下时的容器高度?

问题描述

所以我试图通过为汉字添加笔顺图来调整我的 Anki 抽认卡。

这些图表是由一个名为Kanji Colorizer的插件生成的。

喜欢这个插件,图像是

所以......我想创建一个包含水平图像的滚动框,如果有太多汉字无法并排显示,则水平滚动。

我想我至少在这方面取得了成功。(见下面的代码)。

现在的问题是,虽然盒子水平滚动(如果我启用它,也会垂直滚动),图像仍然保持原样。这意味着我需要允许垂直滚动或接受无用的裁剪图像。

如何调整图像大小以适合框?

澄清:

显示所需调整大小的涂鸦

html 看起来像这样:

<span style="font-size: 20px; "> {{Meaning}} </span>

<hr id=answer>
<tts style="display:none" service="android" voice="ja_JP">{{Expression}}</tts>
<span style="font-size: 40px; ">
{{furigana:Reading}}
</span>
<br>
<div id = "output"></div>
<br>
<button onclick="showHideStrokeOrder()">Stroke Order</button>
<center>
<div id="scrollboxStrokeOrder" style="border:1px solid black;height:150px;width:100%;white-space:nowrap;overflow-y:hidden;overflow-x:auto;display:none">
    <div id='strokeOrderPictures'>{{Stroke Order Diagram}}</div>
</div>
</center>

<script>
function showHideStrokeOrder() {
    var out = document.getElementById("output");

    var scrollbox = document.getElementById("scrollboxStrokeOrder");
    if (scrollbox.style.display === "none") {
       scrollbox.style.display = "block";
    } else {
        scrollbox.style.display = "none";
    };

    var imgs = document.getElementById('strokeOrderPictures');

    var maxHeight= parseFloat(scrollbox.style.height);
    var imgsHeight = imgs.firstChild.height;

    out.innerHTML = "scrollbox height = " + maxHeight + ", imgs height = " + imgsHeight;

    if(imgsHeight > maxHeight) {
        const scale = maxHeight / imgsHeight;
        out.innerHTML += ", scaling = " +scale;

        //this doesn't work and should be replaced, just to clarify intent:
        imgs.style.height = maxHeight;
        imgs.style.width = 'auto';
    };
}
</script>

Where{{Stroke Order Diagram}}是对生成图表图像的卡片字段的引用。在上面的示例中,它包含两张单独的图片,每个汉字一张)。

更新:如果您想尝试一下,将示例共享为可下载的卡片组:

https://ankiweb.net/shared/info/1180304154

标签: javascripthtmlcssimageanki

解决方案


将图像高度与容器匹配

通过 jQuery:

$("#myImg").prop("height", $("#myContainer").prop("height"));

通过 DOM:

document.getElementById("myImg").height=
    document.getElementById("myContainer").height;

带有图像的浏览器 HTML 行为非常慷慨。这会直接将图像大小调整为容器,而不管容器的高度如何(包括使其更大 - 如果您不想要这种行为,您可能需要为此编写更多代码)


推荐阅读