hexo-theme-stellar/source/js/plugins/linkcard.js

49 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-10-25 22:41:56 +08:00
// 本插件由CardLink定制而成原项目源码: https://github.com/Lete114/CardLink
function renderer(el, obj) {
2022-11-04 20:43:26 +08:00
var autofill = [];
const autofillStr = el.getAttribute('autofill');
if (autofillStr) {
autofill = autofillStr.split(',');
}
if (obj.title && obj.title.length > 0 && autofill.includes('title')) {
2022-10-25 23:54:42 +08:00
el.querySelector('.title').innerHTML = obj.title;
2022-11-03 22:25:08 +08:00
el.title = obj.title;
2022-10-25 23:54:42 +08:00
}
2022-11-04 20:43:26 +08:00
if (obj.icon && obj.icon.length > 0 && autofill.includes('icon')) {
2022-10-25 22:41:56 +08:00
el.querySelector('.img').style = 'background-image: url("' + obj.icon + '");';
2022-11-04 20:43:26 +08:00
el.querySelector('.img').setAttribute('data-bg', obj.icon);
2022-10-25 22:41:56 +08:00
}
2022-10-26 23:10:59 +08:00
let desc = el.querySelector('.desc');
2022-11-04 20:43:26 +08:00
if (desc && obj.desc && obj.desc.length > 0 && autofill.includes('desc')) {
2022-10-26 23:10:59 +08:00
desc.innerHTML = obj.desc;
2022-10-25 22:41:56 +08:00
}
}
/**
* Create card links
* @param {NodeList} nodes A collection of nodes or a collection of arrays,
* if it is an array then the array must always contain node element
*/
function setCardLink(nodes) {
// If the `nodes` do not contain a `forEach` method, then the default `a[cardlink]` is used
nodes = 'forEach' in (nodes || {}) ? nodes : document.querySelectorAll('a[cardlink]')
nodes.forEach((el) => {
// If it is not a tag element then it is not processed
if (el.nodeType !== 1) return
2022-11-04 20:43:26 +08:00
el.removeAttribute('cardlink');
const link = el.href;
2022-11-06 15:15:14 +08:00
const api = 'https://api.vlts.cc/site_info/v1?url=';
2022-11-04 20:43:26 +08:00
fetch(api + link).then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
}).then(function(data) {
renderer(el, data);
}).catch(function(error) {
console.log(error);
});
2022-10-25 22:41:56 +08:00
})
}