A-A+
js中不使用blank在新窗口打开链接的方法
有很多朋友会发现在一些网站会碰到很多blank这样的标签直接加在了a之后了,下面我来给各位朋友介绍三种不在a标签加blank的方法,有需要了解的朋友可参考。
思路,在页面载入以后,将rel含有external的a标签,通过js加上target=”_blank“。下面提供jquery方法,代码如下:
- <script type="text/javascript">
- <!--//--><![CDATA[//><!--
- $(document).ready(function() {
- // Find all external links and let them open in a new window.
- $("a.external-link").each(function() {//xiariboke.net
- $(this).click(function() {
- window.open($(this).attr("href"));
- return false;
- });
- });
- });
- //--><!]]>
- </script>
html,代码如下:
- <p>点我在新窗口打开链接
- <a href="https://www.xiariboke.net" class="external-link">网页制作教程</a>
- </p>
js原生方法如下:
- <script type="text/javascript">
- function externalLinks() {
- if (!document.getElementsByTagName) return;
- var anchors = document.getElementsByTagName("a");
- for (var i=0; i<ANCHORS.LENGTH; i++) {
- var anchor = anchors;
- if (anchor.getAttribute(“href”) &&
- anchor.getAttribute(“rel”) == “external”)
- anchor.target = "_blank";
- }
- }
- window.onload = externalLinks;
- </script>
如果你不使用js或jquery来打开新窗口我们可以直接如下,在页面head结束处加上:
- <base target="_blank" />