【发布时间】:2019-03-16 00:31:21
【问题描述】:
注意:请参阅下面的解决方案!
问题
默认情况下,JS 和 jQuery 都会删除空 <foreignObject> 的结束标签。通常这不会是一个问题。但是,在 IE11 中,由于自关闭元素,将引发以下警告。
HTML1500: Tag cannot be self-closing. Use an explicit closing tag.
案例研究
我正在尝试利用 Gulp 将结束标记添加到一系列 SVG 文件中。 SVG 文件最初是这样格式化的:
Email.svg,
<svg width="24" height="24" viewBox="0 0 24 24">
<path fill="#AFAFB0" fill-rule="evenodd" d="M1,5 L23,5 C23.5522847,5 24,5.44771525 24,6 L24,18 C24,18.5522847 23.5522847,19 23,19 L1,19 C0.44771525,19 6.76353751e-17,18.5522847 0,18 L0,6 C-6.76353751e-17,5.44771525 0.44771525,5 1,5 Z M21.2034005,7.09747208 L12,13.8789251 L2.79659952,7.09747208 C2.57428949,6.93366469 2.26127947,6.98109045 2.09747208,7.20340048 C1.93366469,7.42571051 1.98109045,7.73872053 2.20340048,7.90252792 L11.7034005,14.9025279 C11.8797785,15.0324907 12.1202215,15.0324907 12.2965995,14.9025279 L21.7965995,7.90252792 C22.0189095,7.73872053 22.0663353,7.42571051 21.9025279,7.20340048 C21.7387205,6.98109045 21.4257105,6.93366469 21.2034005,7.09747208 Z"/>
</svg>
在我的 gulpfile 中,我使用 gulp-cheerio 尝试通过将结束标记添加到任何自关闭元素来操作 HTML。
gulpfile.js
const gulp = require('gulp');
const cheerio = require('gulp-cheerio');
const rootPath = './src/assets';
const paths = {
svg: {
in: `${rootPath}/icons/raw/**/*.svg`,
out: `${rootPath}/icons/svg`,
}
};
const svg = () => {
return gulp
.src(paths.svg.in)
.pipe(cheerio({
run: ($, file) => {
const updatedHtml = $.html().replace(/<\s*([^\s>]+)([^>]*)\/\s*>/g, '<$1$2></$1>');
// Update self-closing elements to have a closing tag
$('svg').replaceWith(updatedHtml);
}
}))
.pipe(gulp.dest(paths.svg.out));
};
如果我 console.log updatedHtml 它将有结束标签。但是,当我使用.html() 或.replaceWith() 时,输出有一个自闭合标签。
我也试过gulp-replace 包。下面产生与上面相同的结果。
const svg = () => {
return gulp
.src(paths.svg.in)
.pipe(replace(/<\s*([^\s>]+)([^>]*)\/\s*>/g, '<$1$2></$1>'))
.pipe(gulp.dest(paths.svg.out));
};
问题
如何让输出包含结束标记?有没有更好的软件包,或者这真的不可能吗?
【问题讨论】:
-
为什么不简单地将
updatedHtml字符串写入文件? -
这只是 IE 中的一个错误。它是无害的,但据我所知无法抑制。
标签: javascript jquery svg gulp cheerio