[英]Scale images match css selector relative to their size
我必須按比例縮小與以下選擇器匹配的圖像:
img.math
div.math img
問題是我必須將圖像縮小到其自身大小的兩倍(即相對於其自身大小)。 似乎只有javascript才有可能:
width
比例圖像的css技巧 transform
CSS技巧留下空白 我找到了一個js函數,可在此處按比例縮小圖像:
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;
因為OP指出這導致他的圖像變形。
我添加了這一行this.style.height='auto';
如@MorganFeeney所建議。
如果設置了高度,它有助於確保與圖像調整大小成比例。
另外,正如OP所指出的,需要設置this.style.verticalAlign='middle';
。
如果您在對齊方面遇到問題,這可能會有所幫助。 或者,您可以嘗試使用值inherit
或top
。
在某些情況下,此方法可能會有些不准確。
為此,我建議閱讀如何使用javascript或jquery如何獲得圖像的自然尺寸? 以獲得圖像的原始寬度和高度。
另外,您可以閱讀有關跨瀏覽器解決方案的有趣注釋 。
附帶說明:
$(function(){});
等效於:
$(document).ready(function(){});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.