اجعل الروابط الخارجية برتقالية
اجعل جميع الروابط الخارجية برتقالية من خلال تعديل خاصية `النمط 'الخاصة بها.
الرابط يعتبر خارجيا إذا:
- Its
hrefhas://in it - But doesn’t start with
http://internal.com.
Example:
<a name="list">the list</a> <ul> <li><a href="http://google.com">http://google.com</a></li> <li><a href="/tutorial">/tutorial.html</a></li> <li><a href="local/path">local/path</a></li> <li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li> <li><a href="http://nodejs.org">http://nodejs.org</a></li> <li><a href="http://internal.com/test">http://internal.com/test</a></li> </ul> <script> // setting style for a single link let link = document.querySelector('a'); link.style.color = 'orange'; </script> النتيجة يجيب أن تكون:
أولاً ، نحن بحاجة إلى العثور على جميع المراجع الخارجية.
هناك طريقتان.
الأول هو العثور على جميع الروابط باستخدام document.querySelectorAll ('a') ثم تصفية ما نحتاج إليه:
let links = document.querySelectorAll('a'); for (let link of links) { let href = link.getAttribute('href'); if (!href) continue; // no attribute if (!href.includes('://')) continue; // no protocol if (href.startsWith('http://internal.com')) continue; // internal link.style.color = 'orange'; } يرجى ملاحظة ما يلي: نستخدم link.getAttribute ('href'). ليس link.href ، لأننا نحتاج إلى القيمة من HTML.
… طريقة أخرى أبسط هي إضافة الشيكات إلى محدد CSS:
// look for all links that have :// in href // but href doesn't start with http://internal.com let selector = 'a[href*="://"]:not([href^="http://internal.com"])'; let links = document.querySelectorAll(selector); links.forEach(link => link.style.color = 'orange');