簡體   English   中英

如何編輯每個<img>字符串變量的大小(node.js)

[英]How to edit each <img> size in string variable (node.js)

我正在嘗試在字符串變量中編輯圖像大小(寬度和高度),但我需要通過正則表達式對其進行編輯以獲取其寬度和高度,然后將其除以 2。

在示例中:

我在字符串變量中有圖像

const html = `<p><img alt="" src="https://media.cheggcdn.com/media%2F1cb%2F1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1%2Fphp7FkMW8.png"style="height:34px;width:158px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media%2F7f8%2F7f87506b-9fb5-421f-85e6-b283732266d2%2FphprAsgze.png"style="height:130px;width:387px;" /></strong></p>`

如您所見,該變量中有兩個 img 標簽。

第一個圖像大小是: (height:34px;width:158px;)

第二張圖片尺寸為: height:130px;width:387px; .

現在,我需要編輯第一個和第二個圖像大小以取其一半大小

編輯 34px 高度的示例:34/2 = 17 和寬度相同...

所以,新的高度大小是:17px 然后用它的 CSS 樣式替換新的大小

最終結果應該是這樣的:

const HTMl = `<p><img alt="" src="https://media.cheggcdn.com/media%2F1cb%2F1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1%2Fphp7FkMW8.png"style="height:17px;width:79px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media%2F7f8%2F7f87506b-9fb5-421f-85e6-b283732266d2%2FphprAsgze.png"style="height:65px;width:193.5px;" /></strong></p>`

我希望很清楚我需要什么。 你可以通過正則表達式或任何可以做我需要的方法來做到這一點。 謝謝!

在將其設置為 const HTMl變量之前,您可以為 imgs 的高度和寬度創建變量。

const firstImgWidth = 158;
const secondImgWidth = 387;
const firstImgHeight = 34;
const secondImgHeight = 130;

然后您可以使用模板字符串插入這些變量, 請參閱文檔

const html = `<p><img alt="" src="https://media.cheggcdn.com/media%2F1cb%2F1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1%2Fphp7FkMW8.png"style="height:${firstImgHeight}px;width:${firstImgWidth}px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media%2F7f8%2F7f87506b-9fb5-421f-85e6-b283732266d2%2FphprAsgze.png"style="height:${secondImgHeight}px;width:${secondImgWidth}px;" /></strong></p>

這樣,您將能夠輕松地操作<imgs>屬性。

如果可能,您應該查看文檔對象豐富的功能。 MDN 有一些很好的文檔。 一個好的文檔屬性是document.createElement

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM