#97 类名操作


  • 0
    administrators

    完成几个 DOM 元素类名操作的工具方法:

    1. addClass(dom, name):给 dom 元素添加类名 name
    2. removeClass(dom, name):把 dom 元素的类名 name 删除
    3. hasClass(dom, name):判断 dom 元素是否有类名 name

  • 0

    以前没留意到classList的存在,失败。查了下MDN,这是IE10才支持的api,我的代码支持IE9,如果是IE8的话还要写indexOf的shim

    const addClass = (dom, name) => {
      dom.className += ` ${name}`
    }
    
    const removeClass = (dom, name) => {
      let names = dom.className.split(' ')
      let i = names.indexOf(name)
      if(i > -1) {
        names.splice(i,1)
        dom.className = names.join(' ')
      }
    }
    
    const hasClass = (dom, name) => {
      let names = dom.className.split(' ')
      return names.indexOf(name) > -1
    }
    

  • 0

    const addClass = (dom, name) => {
      dom.classList.add(name)
    }
    const removeClass = (dom, name) => {
      dom.classList.remove(name)
    }
    const hasClass = (dom, name) => {
      return dom.classList.contains(name)
    }
    

登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待