copies alt attribute to effective title and makes it more accessible for (user) styles
当前为
// ==UserScript==
// @name img alt to title
// @namespace myfonj
// @include *
// @grant none
// @version 1.0
// @run-at document-start
// @description copies alt attribute to effective title and makes it more accessible for (user) styles
// ==/UserScript==
/*
* Trivia:
* @alt is possible only on IMG
* IMG cannot have children
* @title is possible on any element, including IMG
*
* Goal:
* Pull @alt from image and set it so it is readable as @title tooltip.
*
*
* Process:
* 1) let _alt be IMG@alt
* 2) let _title be IMG@title
* 3) let _titledAncestors be collection of all parents having non-empty @title
* (note: only the title of the "deepest" element - actual hover event target - is normally displayed)
* 4) let _titles be collection of unique @title values from _titledAncestors plus IMG@title, if not empty
* 5) let _title be the last value from _titles
*
* if(!alt && _titles.length)
*
* let title
* _title && !_alt -> `${_title}` // no action
* !_title && _alt -> `Alt: ${_alt}`
* _title == _alt -> `${_title}`
* _title != _alt -> `Alt: ${_alt}${separator}Title: ${_title}`
*
* FROM:
* <a>
* <img alt="¶">
* </a>
* TO:
* <a data-img-alt="Alt: ¶">
* <img alt="¶" title="Alt: ¶">
* </a>
*
* FROM:
* <a>
* <img alt="¶" title="§">
* </a>
* TO:
* <a data-img-alt="¶">
* <img title="Alt: ¶">
* </a>
*
* */
document.documentElement.addEventListener('load', altPic, true);
// document.documentElement.addEventListener('error', altPic, true);
var imageRegister = new WeakMap();
const separator = '\n---\n';
function altPic(event) {
try {
const img = event.target;
if(img.tagName != 'IMG') return
// console.log(img);
var known = imageRegister.get(img);
if(!known) {
known = {};
known.initialTitle = img.title;
known.initialAlt = img.alt;
known.previousTitle = null;
imageRegister.set(img, known);
} else {
if(known.previousTitle === img.title && known.previousAlt === img.alt) {
return
}
}
var titles = getAncestorsTitles(img).map(_=>`Title: ${_}`).join(separator);
if(img.alt) {
titles = `Alt: ${img.alt}${titles?separator+titles:''}`
};
if(!titles) {
if( img.alt === '') {
titles = 'Alt: ""';
} else {
titles = 'Alt missing.';
}
}
img.title = titles
known.previousTitle = titles
} catch(e) { console.error(e)}
}
function getAncestorsTitles(el) {
var ret = [];
do {
if(el.title) {
ret.push(el.title)
}
} while ((el = el.parentNode) && el != document.body);
return ret
}