javascript - 如何调整图像大小以适应按钮按下时的容器高度?
问题描述
所以我试图通过为汉字添加笔顺图来调整我的 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}}
是对生成图表图像的卡片字段的引用。在上面的示例中,它包含两张单独的图片,每个汉字一张)。
更新:如果您想尝试一下,将示例共享为可下载的卡片组:
解决方案
将图像高度与容器匹配
通过 jQuery:
$("#myImg").prop("height", $("#myContainer").prop("height"));
通过 DOM:
document.getElementById("myImg").height=
document.getElementById("myContainer").height;
带有图像的浏览器 HTML 行为非常慷慨。这会直接将图像大小调整为容器,而不管容器的高度如何(包括使其更大 - 如果您不想要这种行为,您可能需要为此编写更多代码)
推荐阅读
- javascript - 为企业注册表 npm 启用审计命令
- node.js - 使用 async.series 和 async.until 的嵌套函数调用上的 nodejs 参考错误
- c# - 在运行时创建 UI 元素的 MVVM 方式是什么?
- php - 在全局设置变量,然后每个`.tpl`文件都可以访问?
- sql-server - 带连接池的 Node.js mssql 数据输入层
- java - 如何让 Netbeans 9 在 Tomcat 上部署有效的 webapp
- wordpress - 如何在 wordpress 的自定义模板页面中插入分页
- javascript - 在设置或获取操作之前如何处理数据?
- javascript - 从表单中获取 id
- python - Pandas 数据框 groupby 函数用法