You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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实例,不能直接读取到值,有两种方法获取属性值:
    1. 用驼峰式属性名直接读取:
    const rawBgValue = targetDiv.style.backgroundImage;
    // 输出结果为:url("https://d14u0p1qkech25.cloudfront.net/club_8702_65d827dd-03b9-4cce-8876-8bd33f306460_thumbnail_250x250")
    
    1. 用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:21:03