如何从href属性获取宽度和高度

时间:2018-12-28 10:36:19

标签: javascript html height width

screenshot

我需要使用VANILLA javascript获取此值-786 x 587 谢谢

4 个答案:

答案 0 :(得分:0)

  • document.querySelector('a [href =“ link”]')。clientWidth
  • document.querySelector('a [href =“ link”]')。clientHeight

答案 1 :(得分:0)

这是代码段

function getImageHeight(link)
{
let img = document.createElement('img');
img.src = "http://picscdn.redblue.de/doi/pixelboxx-mss-76800921/fee_786_587_png/DURACELL-Duracell-BSC-4-db-AA-elem" || link
console.log(img.height)
console.log(img.width)
}

答案 2 :(得分:0)

我尝试使用正则表达式。在下面显示的情况下,console.log将返回URL的widthheight的值

<body>
<a id="tag" href="http://asdfasdfasdf.derp/foo_300x500.png"></a>
<script>
var link = document.getElementById("tag").href;
// pattern for the regex
var pattern = /foo_(\d*)x(\d*).png/g
var result = new RegExp(pattern).exec(link);
console.log(result[1]); // returns first digits (width)
console.log(result[2]); // returns second digits (height)
</script>

</body>

答案 3 :(得分:0)

您需要在访问元素属性之前对其进行缓存

var element = document.getElementsByClassName('t')[0]; document.write(element.getAttribute('href'));
<a class='t' href='value-im-looking-for'>link</a>
<br>
result: