首页 > 解决方案 > 基于windowSize的Linkify(纯url链接)

问题描述

这就是我想做的

  1. 当窗口大小 < 1000 时,将任何纯文本 url 更改为可点击的
  2. 当窗口大小大于 1000 时,将任何纯文本 url 更改为可点击的,替换为“链接”一词。

我试了一下,但似乎在某个地方失败了!

任何人都可以解释一下吗?

谢谢

<html>
<head>
   <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
   <script>$(document).ready(function() {
    function checkWidth() {
        var windowSize = $(window).width();
        if (windowSize < 1000) {
          $('div').each(function(){ $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') ); });
        } //make plain text url clickable
        else if (windowSize < 1000) {
          $('div').each(function(){ $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="Link">Link</a> ') ); });
        } //convert plain text to clickable word "Link"

    }
    checkWidth();
    $(window).resize(checkWidth);
    $(window).onload(checkWidth);
});
  </script>  
</head>  
<body>
  <div>https://www.google.com/</div>
  <div>https://www.yahoo.com/</div> 
  </body>
</html>

标签: jquery

解决方案


我想这就是你要找的。

function checkWidth() {
        var windowSize = $(window).width();
        if (windowSize > 1000) {
          $('div').each(function(){
			var div = $(this).html();
			var link = $(this).find('a');
			var linkText = $(this).find('a').html();
			if(link.length === 0) {
				$(this).html(div.replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> '));
			} else {
				$(this).find('a')[0].innerHTML = $(this).find('a')[0].href;
			}  
		  });
        } //make plain text url clickable
        else if (windowSize < 1000) {
			$('div').each(function(){
				var div = $(this).html();
				var link = $(this).find('a');
				var linkText = $(this).find('a').html();
				if(link.length === 0) {
					$(this).html(div.replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">Link</a> '));
				} else {
					$(this).find('a')[0].innerHTML = 'Link';
				} 
			})
		}//convert plain text to clickable word "Link"
		
    }
    $(document).ready(function() {
        checkWidth();
    });
	//$(window).onload(checkWidth);
	$(window).resize(function(){checkWidth();});
<!DOCTYPE html>
<html>
<head>
   <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
 
</head>  
<body>
  <div>https://www.google.com/</div>
  <div>https://www.yahoo.com/</div> 
  </body>
</html>


推荐阅读