[英]Can I get background-image source's size by javascript?
總是感謝 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')
如果我需要使用而不是背景圖像,該解決方案可能對我有好處另外,是否有好的庫,請推薦我
感謝您有一個愉快的一天
如果您想獲得背景圖像的實際寬度和高度,則可以按照以下步驟操作
像這樣獲取背景圖片的 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";
鑒於這首先加載圖像的事實,您可能需要謹慎使用它,如果這不適用於單個頁面上的大量圖像,那么這可能不是性能下降,但如果比例更大,那么您可能會考慮比在客戶端加載圖像以獲取其實際尺寸更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.