为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

猛跑小猪 2019-11-29 14:52:34
我正在使用以下代码,但在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);
查看完整描述

3 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

   /**

 * 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, ' '));

    }

}


查看完整回答
反对 回复 2019-11-29
  • 3 回答
  • 0 关注
  • 1067 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信