![](/img/trans.png)
[英]@HostListener('document:scroll', []) not working in IE11
[英]IE11 document fragment
我在 angular 2 中创建了一个函数,将 html 字符串转换为 Documents 片段:
private htmlToElement(html): DocumentFragment {
let template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content;
}
它适用于 Chrome 和 Firefox,但对于 IE11,会引发以下错误 ERROR TypeError: Object does not support property or method 'getElementById'。 我调查了它,似乎 template.content 是未定义的。 是否有解决方法使其在 IE11 中也能正常工作? 谢谢!
您可以使用许多 polyfill 选项之一,最小的解决方案可以是https://www.npmjs.com/package/template-polyfill或更复杂的实现https://github.com/webcomponents/polyfills/blob/master /packages/template/template.js
或者您可以使用以下代码,它肯定会更长,不完整,但不会真正慢,并且该原理应该可以帮助您解决问题:
/**
* Convert string to html
*
* @param {string} str - HTML source string
* @param {boolean} multiple - Contains multiple nodes, default: true
*
* @return {null|HTMLElement|NodeList} - Element or collection of elements
*/
export function str2node( str, multiple = true ) {
str = str.trim();
if ( !str.length ) {
return null;
}
/**
* Best practice should be the following, once IE11 support dies, or when using a polyfill
*/
let template = document.createElement( 'template' );
if ( 'content' in template ) {
template.innerHTML = str;
if ( multiple ) {
return template.content.childNodes;
}
return template.content.firstChild;
}
// fix for IE11, with slow detection using div or correct parent element if required
// TODO: check for other special cases with elements requiring a specific parent?
// like: source [ audio video picture ], area [ map ], caption [ table ], option [ select],
// td > tr > table tbody tfoot thead, dt dd > dl
template = document.createElement( str.substr( 0, 4 ) === '<li ' ? 'ul' : 'div' );
template.innerHTML = str;
if ( multiple ) {
return template.childNodes;
}
return template.firstChild;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.