一、JS獲取img的src值
在Web開發中,經常需要獲取圖片的地址,以實現一些預處理或統計工作,此時就需要獲取img元素的src值。
我們可以通過獲取圖片元素並訪問其src屬性來獲取圖片的地址:
let img = document.getElementById('myImage'); let imgSrc = img.src; console.log(imgSrc);
上述代碼中,我們通過getElementById獲取id為myImage的img元素,並通過訪問其src屬性獲取圖片地址,並將其保存在imgSrc變量中。
二、JS獲取img標籤的src
雖然和上一個標題類似,但本小節指的是直接獲取img標籤中的src屬性值,而不是獲取通過DOM操作獲取img元素後的src屬性值。
我們可以通過getAttribute方法獲取img標籤的src:
let imgSrc = document.getElementById('myImage').getAttribute('src'); console.log(imgSrc);
上述代碼中,我們通過getElementById獲取id為myImage的img元素,並通過getAttribute方法獲取img標籤的src,並將其保存在imgSrc變量中。
三、JS獲取img的src屬性
有時候,我們需要獲取img元素的src屬性本身,這時可以用getAttribute方法獲取src屬性:
let imgSrcAttr = document.getElementById('myImage').getAttributeNode('src').value; console.log(imgSrcAttr);
上述代碼中,我們通過getAttributeNode獲取img元素的src屬性節點,並通過value屬性獲取其值,並將其保存在imgSrcAttr變量中。
四、JS獲取img的寬高
有時候需要獲取圖片的寬高,這時可以通過width和height屬性獲取:
let img = document.getElementById('myImage'); let width = img.width; let height = img.height; console.log('寬:' + width + ',高:' + height);
上述代碼中,我們通過getElementById獲取id為myImage的img元素,並通過width和height屬性獲取其寬高,並將其分別保存在width和height變量中。
五、JS怎麼獲取img的src
有三種方式可以獲取img的src:
1. 直接獲取img元素的src屬性值:
let imgSrc = document.getElementById('myImage').src; console.log(imgSrc);
2. 通過getAttribute方法獲取img標籤的src屬性值:
let imgSrcAttr = document.getElementById('myImage').getAttribute('src'); console.log(imgSrcAttr);
3. 通過getAttributeNode方法獲取img元素的src屬性節點:
let imgSrcAttrNode = document.getElementById('myImage').getAttributeNode('src').value; console.log(imgSrcAttrNode);
六、JS獲取img的file
如果我們需要上傳圖片,那麼就需要獲取img的file對象,而不是其src屬性值。可以使用input元素或者new FileReader()方法獲取該對象:
let input = document.getElementById('fileInput'); let file = input.files[0]; console.log(file);
上述代碼中,我們通過id獲取input元素,並通過files屬性獲取其文件列表,從中獲取第一個文件並保存在file變量中。
七、JS獲取img的寬高為0
有時候,使用JS獲取img的寬高可能會出現0的情況,這是因為圖片沒有加載完成,可以採用以下方法解決:
1. 使用window.onload事件:
window.onload = function() { let img = document.getElementById('myImage'); let width = img.width; let height = img.height; console.log('寬:' + width + ',高:' + height); }
2. 使用img元素的onload事件:
let img = document.getElementById('myImage'); img.onload = function() { let width = img.width; let height = img.height; console.log('寬:' + width + ',高:' + height); }
八、JS獲取div里的img
有時候我們需要獲取div等元素中的img標籤,可以使用querySelectorAll方法獲取所有img元素:
let imgList = document.querySelectorAll('div img'); for (let i = 0; i < imgList.length; i++) { console.log(imgList[i].src); }
上述代碼中,我們通過querySelectorAll方法獲取div元素中的所有img元素,並使用循環遍歷所有的img元素,輸出其src屬性值。
原創文章,作者:OKXW,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/147929.html