带有classList的代码在IE中不起作用?

我正在使用以下代码,但在IE中失败。消息是:


无法获取属性'add'的值:对象为null或未定义”


我认为这只是一个IE支持问题。您将如何使以下代码在IE中工作?


有任何想法吗?


var img = new Image();

img.src = '/image/file.png';

img.title = 'this is a title';

img.classList.add("profilePic");

var div = document.createElement("div");

div.classList.add("picWindow");

div.appendChild(img);

content.appendChild(div);


猛跑小猪
浏览 1068回答 3
3回答

温温酱

   /** * Method that checks whether cls is present in element object. * @param  {Object} ele DOM element which needs to be checked * @param  {Object} cls Classname is tested * @return {Boolean} True if cls is present, false otherwise. */function hasClass(ele, cls) {    return ele.getAttribute('class').indexOf(cls) > -1;}/** * Method that adds a class to given element. * @param  {Object} ele DOM element where class needs to be added * @param  {Object} cls Classname which is to be added * @return {null} nothing is returned. */function addClass(ele, cls) {    if (ele.classList) {        ele.classList.add(cls);    } else if (!hasClass(ele, cls)) {        ele.setAttribute('class', ele.getAttribute('class') + ' ' + cls);    }}/** * Method that does a check to ensure that class is removed from element. * @param  {Object} ele DOM element where class needs to be removed * @param  {Object} cls Classname which is to be removed * @return {null} Null nothing is returned. */function removeClass(ele, cls) {    if (ele.classList) {        ele.classList.remove(cls);    } else if (hasClass(ele, cls)) {        ele.setAttribute('class', ele.getAttribute('class').replace(cls, ' '));    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript