ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[toc] ### 1. DOM修改元素内容 `innerHTML `:改变元素的内容,可改变html结构 `textContent` :改变文本的内容,不改变html结构 ``` var test = document.getElementById("test"); test.onclick = function(){ this.innerHTML = "<p>change</p>"; // this.textContent = "<p>change</p>"; } ``` ### 2. DOM修改CSS样式 1. ele.style.cssAttr = "" ``` test.style.color = "red"; ``` 2. ele.className() ``` test.className("none"); ``` 3. ele.style.cssText() ``` test.style.cssText = "color:red; font-weight: bold; font-size:30px" ``` 4. ele.classList ``` ele.classList.add("none"); ele.classList.remove("none"); ele.classList.toggle("none"); test.classList.contains("show") //判断是否包含show,结果返回boolean ``` 5. ele.setAttribute(attr, value) ``` var test = document.getElementById("test"); test.setAttribute("style", "color: red"); test.setAttribute("class", "current"); ``` 6. ele.style.setProperty("color", "yellow"); ele.style.removeProperty("color", "red"); > #### 1. 获取css样式 1. 获取样式表的样式: `getComputedStyle(element).cssAttr` 2. 获取内联样式:`element.style.cssAttr` ``` <div id="test" style="background-color:red;"></div> <script> var test = document.getElementById("test"); // var bg = getComputedStyle(test).backgroundColor; var bg = test.style.backgroundColor; console.log(bg); //red </script> ``` > #### 2. demo-点击显示隐藏 ``` var test = document.getElementById("test"); var btn = document.getElementById("btn"); btn.onclick = function(){ if(test.classList.contains("show")){ test.classList.remove("show"); }else{ test.classList.add("show"); } //test.classList.toggle("show"); } ``` ### 3. 操作元素属性 获取:getAttribute("id") ``` var parent = document.getElementById("parent"); var attr = parent.getAttribute("id"); console.log(attr); ``` 移除:removeAttribute ### 4. 获取元素的大小 #### 1. offset >offset属性只读,不能通过offset方法修改 offsetParent:获取给了定位的父级元素,offset返回number型 offsetLeft:返回元素相对父元素水平偏移位置 offsetTop:返回元素相对父元素垂直偏移位置 offsetWidth:返回元素的宽度(content border padding) offsetHeight:返回元素的高度 #### 2. clientWidth ele.clientWidth:不包括border, margin #### 3. scrollWidth 滚动区域的width, height scrollWidth、scrollHeigth ### 5. 获取元素距离顶部的高度 1. javascript ``` /*向外循环获取offsetTop*/ function getTop(element){ var realTop = element.offsetTop; var parent = element.offsetParent; while(parent !== null) { realTop += parent.offsetTop; parent = parent.offsetParent; } return realTop; } var child = document.getElementById("child"); var top = getTop(child); console.log(top); ``` 2. jQuery offset().top方法