jquery - 基于windowSize的Linkify(纯url链接)
问题描述
这就是我想做的
- 当窗口大小 < 1000 时,将任何纯文本 url 更改为可点击的
- 当窗口大小大于 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>
解决方案
我想这就是你要找的。
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>
推荐阅读
- c++ - 二分查找的终点
- python - Pandas(本机)是否支持 mypy 类型提示?
- canvas - 是否可以在两个形状之间应用 clip() 或 globalCompositeOperation(),然后停止剪辑/合成?
- python - 如何在不知道有多少页面的情况下抓取所有页面
- php - 如何在php hash_pbkdf2中使用字节数组类型的nodejs crypto pbkdf2 salt
- html - 使用 after 伪类选择器后如何删除多余的元素?
- javascript - NodeJS Mongoose - 不从异步函数返回值
- c# - RichTextBox Select + SelectionColor 不起作用
- c# - 如何访问 WPF 中的嵌套属性?
- sql - 在一个查询中结合 SQL Select 和 AVG