首页 > 编程知识 正文

JS 基础篇(classlist兼容性问题)

时间:2023-05-06 02:52:28 阅读:262410 作者:116

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head><body> <div id="classListDom" class="test name ds">ssss</div> <script> // classList , 兼容问题 ,支持IE10典雅的小懒虫 // babel-polyfill.js // polyfill // HTMLDivElement 继承 HTMLElementvar isClsList = 'classList' in HTMLElement.prototype;if(!isClsList) { Object.defineProperty(HTMLElement.prototype,'classList',{ get:function(){ // add, remove ,contains,toggle // this - > var _self = this; return { add:function(cls){ if(!this.contains(cls)){ _self.className +=' ' + cls; } }, remove(cls){ if(this.contains(cls)){ var reg= new RegExp(cls); _self.className = _self.className.replace(reg,''); } }, contains(cls){ var index = _self.className.indexOf(cls); return index!=-1 ? true : false; }, toggle(cls){ if(this.contains(cls)){ this.remove(cls) } else { this.add(cls) } } } } })}var classListDom = document.getElementById('classListDom');classListDom.classList.contains('test')classListDom.classList.add('ok')classListDom.classList.toggle('ok') </script></body></html>

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。