總是感謝 stackoverflow 的每個人
我做了一個 div,它包括 background-image: url(imageURL) 像這樣的代碼
HTML >
<div ref={mapRef} className="image-container" style={{ backgroundPosition: '0 0' }} >
{markersState}
</div>
CSS >
.image-container {
width: 1024px;
height: 768px;
cursor: grab;
user-select: none;
background-image: url("/images/map.png");
background-position: 0 0;
background-repeat: no-repeat;
}
我想獲取背景影像源(=”/images/map.png')的大小我怎樣才能得到它?(源的寬度:2907px,高度:'3460px')
如果我需要使用而不是背景影像,該解決方案可能對我有好處另外,是否有好的庫,請推薦我
感謝您有一個愉快的一天
uj5u.com熱心網友回復:
如果您想獲得背景影像的實際寬度和高度,則可以按照以下步驟操作
像這樣獲取背景圖片的 URL ( https://stackoverflow.com/a/45010803/1391805 )
var css = document.getElementById("myElem").style.backgroundImage;
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");
獲得影像 URL 后,執行此操作
var newImg = new Image();
newImg.onload = function(e) {
console.log( this.naturalWidth ); // This is the width you are looking for
console.log( this.naturalHeight ); // .. similarly the height.
}
newImg.src = "img.jpg";
鑒于這首先加載影像的事實,您可能需要謹慎使用它,如果這不適用于單個頁面上的大量影像,那么這可能不是性能下降,但如果比例更大,那么您可能會考慮比在客戶端加載影像以獲取其實際尺寸更好的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328513.html
標籤:javascript html css 反应
上一篇:CSS標題邊框底部
下一篇:如何使用CSS將選項框向右移動?
