這是我的決議器:
let getFavicon = function () {
let favicons = [];
let nodeList = document.getElementsByTagName('link');
for (let i = 0; i < nodeList.length; i ) {
if (
nodeList[i].getAttribute('rel') === 'icon' ||
nodeList[i].getAttribute('rel') === 'shortcut icon'
) {
favicons.push(nodeList[i].getAttribute('href'));
}
}
return favicons;
};
它回傳一個包含所有 URL 圖示的 URL 陣列。
用戶如何獲得這些網站圖示?在輸入中輸入 URL 并獲取網站圖示時。
像谷歌標簽一樣,我們輸入 URL 并獲取帶有 favicon 的標簽


我怎么能做同樣的事情?
uj5u.com熱心網友回復:
我希望這個例子會有所幫助:
let favicons = [];
let nodeList = document.getElementsByTagName("link");
for (let i = 0; i < nodeList.length; i ) {
if ((nodeList[i].getAttribute("rel") === "icon") || (nodeList[i].getAttribute("rel") === "shortcut icon")) {
favicons.push(nodeList[i].getAttribute("href"))
}
}
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j ) {
if (strArray[j].match(str)) return strArray[j];
}
return -1;
}
const searchTextBox = document.querySelector('input[name="search"]')
searchTextBox.addEventListener('keyup', (e) => {
const searchResult = searchStringInArray(e.target.value, favicons)
if(searchResult != -1){
document.querySelector('.icon').style.background = `url('${searchResult}')`
}
})
.icon {
height: 35px;
width: 35px;
display: block;
}
<head>
<link rel="shortcut icon" href="https://abs.twimg.com/favicons/twitter-pip.ico" type="image/x-icon">
<link rel="icon" href="https://www.youtube.com/s/desktop/6e57b52d/img/favicon_48x48.png" sizes="48x48">
<link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196">
</head>
<input name="search" type="text">
<span class='icon'></span>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318165.html
標籤:javascript 解析 dom
