【发布时间】:2017-03-07 12:38:00
【问题描述】:
以下脚本适用于大多数静态网站和超链接,但目前在为 wiki 和其他动态生成的内容呈现工具提示时存在问题。
我什至在调用tooltipster()之前使用了超时等待所有内容加载,但这仍然没有呈现工具提示。
setTimeout(function() {
$('a.tooltipster').tooltipster({
theme: 'tooltipster-punk'
});
}, 5000);
它在jQuery 和MDN 等网站上运行良好,但在Wikipedia 和Reddit 上运行良好。
用户脚本
// ==UserScript==
// @name Link Hover
// @namespace default
// @version 1.0.0
// @description Display link.
// @author Mr. Polywhirl
// @match *://*/*
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.slim.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/js/jquery.tooltipster.min.js
// @resource tt_CSS https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/tooltipster.min.css
// @resource ttTheme_CSS https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/themes/tooltipster-punk.min.css
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_log
// ==/UserScript==
(function() {
'use strict';
GM_addStyle([
GM_getResourceText('tt_CSS'),
GM_getResourceText('ttTheme_CSS')
].join(''));
(function($) {
$.fn.setLinkTitle = function() {
return this.attr('title', processLink(this.attr('href')));
};
})(jQuery);
$(function() {
$('a').each((index, link) => {
$(link).addClass('tooltipster').setLinkTitle();
}).tooltipster({
theme: 'tooltipster-punk'
});
});
function processLink(path) {
return !isPathAbsolute(path) ? relPathToAbs(path) : path;
}
// http://stackoverflow.com/a/25833886/1762224
function relPathToAbs(sRelPath) {
var nUpLn, sDir = "", sPath = location.pathname.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, "$1"));
for (var nEnd, nStart = 0; nEnd = sPath.indexOf("/../", nStart), nEnd > -1; nStart = nEnd + nUpLn) {
nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp("(?:\\\/+[^\\\/]*){0," + ((nUpLn - 1) / 3) + "}$"), "/");
}
return location.protocol + '//' + location.host + sDir + sPath.substr(nStart);
}
function isPathAbsolute(path) {
return /^(?:\/|[a-z]+:\/\/)/.test(path);
}
})();
【问题讨论】:
-
控制台中有一个错误提示
path未定义,因为href属性为空。这可能是 Chrome 中的一个错误,但我没有正确调查它(现在没有时间)。您可以使用$.fn.setLinkTitle = function() { this[0].title = processLink(this[0].href); };另外,请考虑使用URL API。
标签: javascript jquery userscripts tampermonkey tooltipster