如何用JavaScript获取元素background-image的宽高及样式获取异常问题
问题解答
一、为什么直接用element.style获取不到样式?
element.style只能读取元素内联样式(也就是写在<div style="...">标签里的样式),而你的CSS样式是定义在外部样式表或<style>标签中的「计算样式」,所以直接调用element.style会返回空的CSSStyleDeclaration对象。要获取这类样式,必须用window.getComputedStyle()方法。
比如你可以这样正确获取background-image:
const element = document.getElementsByClassName('current-img')[0]; const computedStyle = window.getComputedStyle(element); const bgImageUrl = computedStyle.backgroundImage; // 提取纯URL(返回值默认带url(...)包裹) const pureUrl = bgImageUrl.replace(/^url\(['"]?(.*?)['"]?\)$/, '$1');
二、如何获取background-image的宽高?
可以通过创建Image对象加载背景图URL,等图片加载完成后获取原始宽高,在Selenium中可以通过execute_script执行以下逻辑:
JavaScript核心逻辑
return new Promise((resolve) => { const element = document.querySelector('.current-img'); const computedStyle = window.getComputedStyle(element); // 提取背景图URL const urlMatch = computedStyle.backgroundImage.match(/^url\(['"]?(.*?)['"]?\)$/); if (!urlMatch) { resolve(null); return; } const bgImageUrl = urlMatch[1]; const img = new Image(); img.onload = () => { resolve({ width: img.width, height: img.height }); }; // 处理图片加载失败的情况 img.onerror = () => { resolve(null); }; img.src = bgImageUrl; });
以Python版Selenium调用为例
bg_img_dimensions = driver.execute_async_script(""" return new Promise((resolve) => { const element = document.querySelector('.current-img'); const computedStyle = window.getComputedStyle(element); const urlMatch = computedStyle.backgroundImage.match(/^url\(['"]?(.*?)['"]?\)$/); if (!urlMatch) { resolve(null); return; } const bgImageUrl = urlMatch[1]; const img = new Image(); img.onload = () => { resolve({ width: img.width, height: img.height }); }; img.onerror = () => { resolve(null); }; img.src = bgImageUrl; }); """) print(bg_img_dimensions) # 输出示例:{'width': 1920, 'height': 1080}
注意:如果背景图是相对路径,浏览器会自动补全为绝对路径,无需额外处理;务必添加加载失败的回调,避免Promise一直处于pending状态。
内容的提问来源于stack exchange,提问作者zaelcovsky
相关产品推荐
相关产品推荐

