使用querySelector获取div的style中background-image对应url值方法咨询
解决步骤
- 首先修正元素选择器的错误:你当前的
document.querySelector('rounded-ca')存在两个问题,一是类名拼写错误(目标元素类是rounded-ch不是rounded-ca),二是类选择器需要加.前缀,正确写法如下:
const targetDiv = document.querySelector('.rounded-ch');
- 获取background-image的原始值
你拿到的类数组格式的style对象是DOM的CSSStyleDeclaration实例,不能直接读取到值,有两种方法获取属性值:- 用驼峰式属性名直接读取:
const rawBgValue = targetDiv.style.backgroundImage; // 输出结果为:url("https://d14u0p1qkech25.cloudfront.net/club_8702_65d827dd-03b9-4cce-8876-8bd33f306460_thumbnail_250x250")- 用
getPropertyValue方法传入中划线格式的属性名:
const rawBgValue = targetDiv.style.getPropertyValue('background-image'); - 提取纯URL内容
拿到带url()包裹的原始值后,用简单的正则即可提取出纯url:
const imageUrl = rawBgValue.match(/url\(['"]?(.*?)['"]?\)/)?.[1];
如果确定格式固定,也可以用字符串裁剪的方法:
const imageUrl = rawBgValue.slice(5, -2);
内容的提问来源于stack exchange,提问作者Innextinit
相关产品推荐
相关产品推荐

