Welcome

カキノタblog

自分の興味あるテーマを中心に、図解多めに記事を作成していきたいと思います。

Quill ToolbarのButtonにTooltip(hint)を表示する

デフォルトではTooltipsを表示する機能が用意されていないので自分でカスタマイズする必要があります。

方法1

var quill = new Quill('.editor', {
	theme: 'snow'
});

function showTooltips(){
	let toolbarElement = document.querySelector('.ql-toolbar');
	if (toolbarElement) {
		let matches = toolbarElement.querySelectorAll('button');
		for (let btnEl of matches) {
			let btnName = btnEl.className.replace('ql-', '');
			btnName = btnName.charAt(0).toUpperCase() + btnName.slice(1)
			btnEl.setAttribute("title", btnName)
		}
	}
}

showTooltips()

ボタンのクラス名を利用してボタン名として表示させています。

方法2

let toolbarTooltips = {
	'font': 'Select a font',
	'size': 'Select a font size',
	'header': 'Select the text style',
	'bold': 'Bold',
	'italic': 'Italic',
	'underline': 'Underline',
	'strike': 'Strikethrough',
	'color': 'Select a text color',
	'background': 'Select a background color',
	'script': {
		'sub': 'Subscript',
		'super': 'Superscript'
	},
	'list': {
		'ordered': 'Numbered list',
		'bullet': 'Bulleted list'
	},
	'indent': {
		'-1': 'Decrease indent',
		'+1': 'Increase indent'
	},
	'direction': {
		'rtl': 'Text direction (right to left | left to right)',
		'ltr': 'Text direction (left ro right | right to left)'
	},
	'align': 'Text alignment',
	'link': 'Insert a link',
	'image': 'Insert an image',
	'formula': 'Insert a formula',
	'clean': 'Clear format',
	'add-table': 'Add a new table',
	'table-row': 'Add a row to the selected table',
	'table-column': 'Add a column to the selected table',
	'remove-table': 'Remove selected table',
	'help': 'Show help'
};

function showTooltips() {
	let showTooltip = (which, el) => {
		if (which == 'button') {
			var tool = el.className.replace('ql-', '');
		}
		else if (which == 'span') {
			var tool = el.className.replace('ql-', '');
			tool = tool.substr(0, tool.indexOf(' '));
		}
		if (tool) {
			//if element has value attribute.. handling is different
			//buttons without value
			if (el.value == '') {
				if (toolbarTooltips[tool])
					el.setAttribute('title', toolbarTooltips[tool]);
			}
			//buttons with value
			else if (typeof el.value !== 'undefined') {
				if (toolbarTooltips[tool][el.value])
					el.setAttribute('title', toolbarTooltips[tool][el.value]);
			}
			//default
			else
				el.setAttribute('title', toolbarTooltips[tool]);
		}
	};

	let toolbarElement = document.querySelector('.ql-toolbar');
	if (toolbarElement) {
		let matchesButtons = toolbarElement.querySelectorAll('button');
		for (let el of matchesButtons) {
			showTooltip('button', el);
		}
		//for submenus inside 
		let matchesSpans = toolbarElement.querySelectorAll('.ql-toolbar > span > span');
		for (let el of matchesSpans) {
			showTooltip('span', el);
		}
	}
}

showTooltips()

https://github.com/quilljs/quill/issues/650#issuecomment-541002924

こちらのソースコードを丸ごと転載させていただきました。

参考リンク