直接访问元素的 src 和 getAttribute('src') 的区别

312 阅读1分钟

比如 HTML 有这样一个 img 图片标签:

<img src="a.png">

使用 JS 获取图片的 src 有两种方式。

方式一:元素.attribute('src')

console.log(img.getAttribute('src')) // a.png

HTML 中的元素的 src 是什么,那么 getAttribute() 得到的就是什么。

方式二:元素.src

console.log(img.src) // http://xxx/a.png

.src 返回解析之后的绝对 URL,即使 HTML 中的内容是相对 URL。比如:

  • 当前网页路径是 http://example.com/,则解析之后的是 http://example.com/a.png
  • 当前网页路径是 http://example.com/a,则解析之后的是 http://example.com/a.png
  • 当前网页路径是 http://example.com/a/b,则解析之后的是 http://example.com/a/a.png

总结

  • 元素.attribute('src') 获取到的永远是 HTML 中的元素 src
  • 元素.src 获取解析之后的绝对 URL,即使 HTML 中的内容是相对 URL
  • 该规则同样适用于 script、link 等带有 srchref 的元素