gpt4 book ai didi

javascript - 缩放图像相对于它们的大小匹配 css 选择器

转载 作者:行者123 更新时间:2023-11-28 12:34:49 24 4
gpt4 key购买 nike

我必须缩小与以下选择器匹配的图像:

img.math
div.math img

问题是我必须将图像缩小两倍于它们自身的大小——这是相对于它们自身的大小。似乎只有使用 javascript 才有可能:

  • css 技巧 width 相对于当前行宽度缩放图像
  • css 技巧与 transform leave empty space

我找到了一个缩小图像的 js 函数 here :

function Resize(imgId)
{
var img = document.getElementById(imgId);
var w = img.width, h = img.height;
w /= 2; h /= 2;
img.width = w; img.height = h;
}

现在的问题是将该函数应用于匹配上述选择器的图像。

我使用的是 jQuery 1.11,应该是这样的:

// resize all math images:
$(document).ready(function() {
$("img.math").each(function() {
// ???
});
$("div.math img").each(function() {
// ???
});
});

(这是更大的部分 (function ($) { }(window.$jqTheme || window.jQuery));)

编辑:

img.math 只是一个内联图像。 div.math img 是一个带编号的数学方程式:它还包含方程式编号,即向右浮动的 span

编辑 2:完成 html 部分示例

涉及的 html 非常基础:

<div id="math" class="section">
<span id="id1"></span><h1>Math</h1>
<p>In-line equation: <img alt="a^2+b^2=c^2" src="_images/math/ee657daf07808119b97144fc459a5dc8839eb9c9.png" class="math">.</p>
<p>Numbered equation:</p>
<div id="equation-pythag" class="math">
<p><span class="eqno">(1)</span><img alt="a^2 + b^2 = c^2" src="_images/math/53158707cc080d32d0d2f081e4bf5c6988f437ca.png"></p>
</div><p>Link to equation: <a href="#equation-pythag">(1)</a>.</p>
</div>

所有图像都是静态定位的:img.math 只是一个内联图像,而 div.math img 在 div 中水平居中。

最佳答案

这些信息不足以发表评论,但也不足以回答。

不过,我还是会回答的。

您的代码必须重写为以下内容:

// resize all math images:
$(function() {
$("img.math, div.math img").each(function() {
this.width/=2;
this.style.height='auto'; //ensures proportion
this.style.verticalAlign='middle';
});
});

可以安全地删除所有样板代码。

我删除了 this.height/=2; 行,因为 O.P. 表示它导致他的图像变形。

我按照@MorganFeeney 的建议添加了 this.style.height='auto'; 行。
它有助于确保与图像调整大小成比例,以防它设置的高度。

此外,正如 O.P. 指出的那样,需要设置 this.style.verticalAlign='middle';
如果您在对齐方面遇到问题,这可能会有所帮助。或者您可以尝试值 inherittop

这种方法在某些情况下可能有点不准确。
为此,我建议阅读 How do I get natural dimensions of an image using javascript or jquery?获取图像的原始宽度和高度。
另外,您可以阅读 this interesting comment用于跨浏览器解决方案。


作为旁注:

$(function(){});

相当于:

$(document).ready(function(){});

关于javascript - 缩放图像相对于它们的大小匹配 css 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27959861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com