56 lines
2.0 KiB
JavaScript
56 lines
2.0 KiB
JavaScript
//提供四个对象,可以来写dom逻辑
|
|
//html,documentument,cfg,pages
|
|
|
|
/**
|
|
* 从提供的 `documentument` 中移除所有 style 中含有 `page-break-after: always` 的声明。
|
|
* - 处理 inline `style` 属性
|
|
* - 处理 `<style>` 元素中的 CSS 文本
|
|
*
|
|
* 用法:
|
|
* import { removePageBreakAfterAlways } from './build.js';
|
|
* removePageBreakAfterAlways(documentument);
|
|
*/
|
|
if (!document || typeof document.querySelectorAll !== 'function') return;
|
|
|
|
// 1) 处理 inline style 属性
|
|
const inlineEls = Array.from(document.querySelectorAll('[style]'));
|
|
inlineEls.forEach(el => {
|
|
try {
|
|
// 首先尝试通过 element.style API 移除(标准情况)
|
|
const val = (el.style && el.style.getPropertyValue('page-break-after')) || '';
|
|
if (val && val.trim().toLowerCase().startsWith('always')) {
|
|
el.style.removeProperty('page-break-after');
|
|
if (!el.getAttribute('style') || el.getAttribute('style').trim() === '') {
|
|
el.removeAttribute('style');
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 兜底:直接在 attribute 字符串上替换(处理非标准或复杂写法)
|
|
const original = el.getAttribute('style') || '';
|
|
const replaced = original.replace(/page-break-after\s*:\s*always(?:\s*!important)?\s*;?/ig, '');
|
|
if (replaced !== original) {
|
|
// 清理多余分号与空白
|
|
const cleaned = replaced.replace(/;{2,}/g, ';').replace(/\s*;\s*$/,'').trim();
|
|
if (!cleaned) el.removeAttribute('style');
|
|
else el.setAttribute('style', cleaned);
|
|
}
|
|
} catch (e) {}
|
|
});
|
|
|
|
// 2) 处理 <style> 元素中的文本
|
|
const styleEls = Array.from(document.querySelectorAll('style'));
|
|
styleEls.forEach(styleEl => {
|
|
try {
|
|
const original = styleEl.textContent || '';
|
|
const replaced = original.replace(/page-break-after\s*:\s*always(?:\s*!important)?\s*;?/ig, '');
|
|
// 移除空的规则块,例如 `selector { }`
|
|
let cleaned = replaced.replace(/[^\{\}]+\{\s*\}/g, '');
|
|
// 多余空白归一
|
|
cleaned = cleaned.replace(/\n{2,}/g, '\n').trim();
|
|
if (cleaned !== original) styleEl.textContent = cleaned;
|
|
} catch (e) {}
|
|
});
|
|
|
|
|