可以获取当前的dom元素并检查是否为h1
setInterval(function () {
var isBold = document.queryCommandState("Bold");
var isItalic = document.queryCommandState("Italic");
var isUnderlined = document.queryCommandState("Underline");
var el = getSelectionContainerElement();
if($(el).is('h1')){
$('button[rel="Primary Heading"]').addClass('active');
}else{
$('button[rel="Primary Heading"]').removeClass('active');
}
if (isBold) {
$('button[rel=Bold]').addClass('active');
} else {
$('button[rel=Bold]').removeClass('active');
}
if (isItalic) {
$('button[rel=Italic]').addClass('active');
} else {
$('button[rel=Italic]').removeClass('active');
}
if (isUnderlined) {
$('button[rel=Underline]').addClass('active');
} else {
$('button[rel=Underline]').removeClass('active');
}
}, 100)
以下函数复制自:如何使用 Javascript 在浏览器的可编辑内容窗口中找出光标处的 DOM 节点?
function getSelectionContainerElement() {
var range, sel, container;
if (document.selection && document.selection.createRange) {
// IE case
range = document.selection.createRange();
return range.parentElement();
} else if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
} else {
// Old WebKit selection object has no getRangeAt, so
// create a range from other selection properties
range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the document)
if (range.collapsed !== sel.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
}
if (range) {
container = range.commonAncestorContainer;
// Check if the container is a text node and return its parent if so
return container.nodeType === 3 ? container.parentNode : container;
}
}
}