猿问

在 html 正文中显示每个网站的图标

我试图在 html 中显示标签和 url。是否可以显示来自互联网的每个网址的图标?(我想自动显示图标,而不是在每个之前添加)

这可能吗?


元芳怎么了
浏览 157回答 3
3回答

人到中年有点甜

假设您的 HTML 看起来像这样:<ul>&nbsp; <li class="link"><a href="https://google.com">Google.com</a></li>&nbsp; <li class="link"><a href="https://stackoverflow.com">Stackoverflow.com</a></li>&nbsp; <li class="link"><a href="https://example.com">Example.com</a></li></ul>您可以添加脚本标记并循环遍历列表中的每个项目,将标准 favicon 文件名 (favicon.ico) 附加到该项目的 url,然后使用该 url 作为源创建一个图像元素例子:<ul>&nbsp; <li class="link"><a href="https://google.com">Google.com</a></li>&nbsp; <li class="link"><a href="https://stackoverflow.com">Stackoverflow.com</a></li>&nbsp; <li class="link"><a href="https://example.com">Example.com</a></li></ul><script>&nbsp; for (let element of document.getElementsByClassName("link")) {&nbsp; &nbsp; var faviconImage = document.createElement("img");&nbsp; &nbsp; faviconImage.src = element.children[0].href + "/favicon.ico";&nbsp; &nbsp; faviconImage.classList = "faviconImage";&nbsp; &nbsp; element.appendChild(faviconImage)&nbsp; }</script>

茅侃侃

您可以使用 Google 图标抓取工具:<a href="https://stackoverflow.com">&nbsp; Stackoverflow.com&nbsp; <img src="https://www.google.com/s2/favicons?domain=stackoverflow.com"></a>

慕后森

以下代码会将网站图标添加到所有链接(内部链接或非 http 链接除外)之前,这些链接均包装在带有favicon类的父容器内。此外,就速度而言,最好使用 Google 的图标抓取器,而不是像 Lebster 在他的回答中所示手动从每个域中抓取它。var host = window.location.host;var links = document.querySelectorAll('.favicon a');var googleFaviconGrabber = "https://www.google.com/s2/favicons?domain=";for (i = 0; i < links.length; i++) {&nbsp; var link = links[i];&nbsp; // Skip all internal links and non HTTP links&nbsp; if (link.href.match("^https?://") && !link.href.match(host)) {&nbsp; &nbsp; var domain = link.href.split("/");&nbsp; &nbsp; // Apply some CSS styles to the hyperlinks&nbsp; &nbsp; link.style.background = "url(" + googleFaviconGrabber + domain[2] + ") center left no-repeat";&nbsp; &nbsp; link.style.fontWeight = "bold";&nbsp; &nbsp; link.style.padding = "5px 5px 5px 20px";&nbsp; &nbsp; link.style.textDecoration = "underline";&nbsp; }}<div class="favicon">&nbsp; This demo shows how to add favicons to external links using javascript. Check out this link to&nbsp; <a href="https://codegena.com">Codegena</a>.&nbsp; <ul>&nbsp; &nbsp; <li> <a href="https://css-tricks.com/">CSS Tricks</a></li>&nbsp; &nbsp; <li><a href="https://google.in">Google</a></li>&nbsp; &nbsp; <li><a href="http://unheap.com">Unheap</a></li>&nbsp; &nbsp; <li><a href="http://www.canva.com/">Canva</a></li>&nbsp; </ul></div>
随时随地看视频慕课网APP

相关分类

Html5
我要回答