
标准attribute:某些attribute属性是标准的,比如id、class、href、type、value等;
非标准attribute:某些attribute属性是自定义的,比如age、height等
hohh
elem.hasAttribute(name) — 检查特性是否存在。 elem.getAttribute(name) — 获取这个特性值。 elem.setAttribute(name, value) — 设置这个特性值。 elem.removeAttribute(name) — 移除这个特性。 attributes:attr对象的集合,具有name、value属性;
attribute
4.JavaScript动态修改样式
方式一:动态添加class修改样式
编写好对应的样式,动态添加样式的class
2222
方式二:动态修改style属性
2222
5.元素的className和classList
class对应的property并非叫class,而是className
这是因为js早期不允许使用class这样的关键字来作为对象的属性,所以DOM规范使用了className;虽然现在js已经没有这样的限制,但是不推荐,并且依然在使用className这个名称
我们可以对className进行赋值,但是它会替换整个类中的字符串,所以想要添加或者移除单个的class,那么可以使用classList属性。
elem.classList 是一个特殊的对象:
elem.classList.add (class) :添加一个类elem.classList.remove(class):添加/移除类。elem.classList.toggle(class) :如果类不存在就添加类,存在就移除它。elem.classList.contains(class):检查给定类,返回 true/false。classList是可迭代对象,可以通过for of进行遍历
6.元素的style属性
如果需要单独修改某一个css属性,那么可以通过style来 *** 作
如果多词属性,使用驼峰式camelCase如果我们将值设置为空字符串,那么会使用css的默认样式boxEl.style.width = "100px" boxEl.style.backgroundColor = "red"多个样式的写法,我们需要使用cssText属性(不推荐,因为它会替换整个字符串)boxEl.style.display = ""
7.元素的 *** 作 7.1.创建元素元素style的读取-getComputedStyle
如果我们需要读取样式
对于内联样式,是可以通过style.*的方式读取到的;对于style、css文件中的样式。是读取不到的这个时候,我们可以通过getComputedStyle的全局函数来实现
console.log(getComputedStyle(boxEl).width) console.log(getComputedStyle(boxEl).backgroundColor)
document.createElement(tag)
创建一个tag标签的元素
var boxEl = document.querySelector(".box")
var h2El = document.createElement("h2")
h2El.innerHTML = "我是标题"
h2El.classList.add("title")
boxEl.append(h2El)
7.2.插入元素
node.append(...nodes or strings) —— 在 node 末尾 插入节点或字符串, node.prepend(...nodes or strings) —— 在 node 开头 插入节点或字符串, node.before(...nodes or strings) —— 在 node 前面 插入节点或字符串, node.after(...nodes or strings) —— 在 node 后面 插入节点或字符串, node.replaceWith(...nodes or strings) —— 将 node 替换为给定的节点或字符串。7.3.移除和克隆元素
node.remove() 移除元素我们可以调用元素本身的remove方法
如果我们想要赋值一个现有的元素,可以通过cloneNode方法
可以传入一个Boolean类型的值,来决定是否是深度克隆;深度克隆会克隆对应元素的子元素
var cloneBoxEl = boxEl.cloneNode(true)
document.body.append(cloneBoxEl)
7.4.旧的元素 *** 作方法
7.5.元素的大小、滚动在很多地方我们也会看到一些旧的 *** 作方法:
parentElem.appendChild(node): 在parentElem的父元素最后位置添加一个子元素parentElem.insertBefore(node, nextSibling): 在parentElem的nextSibling前面插入一个子元素;parentElem.replaceChild(node, oldChild): 在parentElem中,新元素替换之前的oldChild元素;parentElem.removeChild(node): 在parentElem中,移除某一个元素;
clientWidth:contentWith+padding(不包含滚动条)clientHeight:contentHeight+paddingclientTop:border-top的宽度clientLeft:border-left的宽度offsetWidth:元素完整的宽度offsetHeight:元素完整的高度offsetLeft:距离父元素的xoffsetHeight:距离父元素的yscrollHeight:整个可滚动的区域高度scrollTop:滚动部分的高度8.window的大小、滚动
window的width和height
innerWidth、innerHeight:获取window窗口的宽度和高度(包含滚动条)outerWidth、outerHeight:获取window窗口的整个宽度和高度(包括调试工具、工具栏)window的滚动位置
scrollX:X轴滚动的位置(别名pageXOffset)scrollY:Y轴滚动的位置(别名pageYOffset)滚动方法
方法scrollBy(x, y):将页面滚动至相对当前位置的(x, y)位置方法scrollTo(pageX, pageY)将页面滚动至绝对坐标
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)