[英]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.