current position:Home>Dom, JS/CSS interaction

Dom, JS/CSS interaction

2022-09-23 06:42:14kind amumu

与css的交互

className属性

<script>
var len=document.getElementsByTagName("li");
for(var i=0;i<len.length;i++){
	len[i].onmouseover=function(){
		this.className="over";
		}
	len[i].onmouseout=function(){
		this.className="out";
		}	
	}
<script>

classList属性
元素classListAttributes can get all classes of an element---类数组.
方法:
add(类名1,类名2,....):Add a new class to the original class.
remove(类名1,类名2,....):删除指定的类.
toggle(类名):切换,If there is a class with the specified class name, it will be deleted,否则就添加.
contains(类名):判断元素classListWhether to include the specified class in .含有返回true,不含有返回false
item(索引):获取classListSpecifies the class name of the index.

.ClassListProperties have the following methods:

(1)通过ClassListYou can get the full class name of the element;

(2)通过ClassList.remove()One or more class names from which elements can be removed;

(3)通过ClassList.add()One or more class names can be added to an element;

(4)通过ClassList.lentghThe number of element class names that can be obtained;

(5)通过ClassList.item(x)The index of the element class name can be obtainedx的类名;

(6)通过ClassList.toggleCan switch classes for elements;

(7)通过ClassList.contains(x)Check to see if the element exists with the class name"x"的类;

 <script>
类操作:
    增加类:
    dom对象.classList.add("类名1", "类名2", ...)
    删除类:
    dom对象.classList.remove("类名1", "类名2", ...)
    删除/添加类
    dom对象.classList.toggle("类名")  如果domObject contains this class,Remove this class,如果没有这个类,Add this class
    dom对象.classList.toggle("类名",参数2)
    参数2:可选 布尔值  如果为false,Indicates to delete a class,如果为true,Indicates adding a class

    dom对象.classList.contains("类") 判断dom对象是否含有某个类  If it contains such returntrue,否则返回false
 </script>

样式操作

 获取样式

     w3cStandard browsers get computed styles

     getComputedStyle(dom对象).样式属性名

     ie8及以下版本

     dom对象.currentStyle.样式属性名

 兼容 w3c 和 ie的方式,封装函数,调用

<script>
//1.
function getStyle(elem, name) {
        if (elem.currentStyle) {//ie8及以下版本
            return elem.currentStyle[name];
        } else if (getComputedStyle) {
            return getComputedStyle(elem)[name];
        }
    }

//2.
 try {
        w = getComputedStyle(oDiv).width;
    } catch (err) {
        w = oDiv.currentStyle.width;
    }
</script>

scroll系列 

  • dom对象.scrollLeft
    获取/设置domThe distance the object's horizontal scroll bar scrolls
  • dom对象.scrollTop
    获取/设置domThe distance the object's vertical scroll bar scrolls
  • dom对象.scrollWidth
    获取dom对象的实际内容的宽度
  • dom对象.scrollWidth
    获取dom对象的实际内容的宽度

offset系列

 

  • dom对象.offsetParent是拥有position属性,并且值为relative、absolute或fixed的父容器,If the parent container doesn't have oneposition属性,则为body
  • dom对象.offsetLeft
    获取domobject distanceoffsetParent左侧的距离
  • dom对象.offsetTop
    获取domobject distanceoffsetParentdistance from the top
  • dom对象.offsetWidth
    获取domThe width of the object box
  • dom对象.offsetHeight
    获取domThe height of the object box

offset的使用

<script>
    var oDiv = document.getElementById("box");
    // console.log(oDiv.offsetParent);//body  .container
    // console.log(oDiv.offsetLeft);
    // console.log(oDiv.offsetTop);
    console.log(oDiv.offsetWidth);
    console.log(oDiv.offsetHeight);

    dom对象.offsetTop 获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计算上侧位置 .
    获取domObject distance from the canvas oroffsetParentdistance from the top

    dom对象.offsetLeft 获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置.
    获取domObject distance from the canvas oroffsetParent左侧的距离

    offsetParent:布局中设置position属性(Relative、Absolute、fixed)的父容器,Or the parent element Nonepostion,从最近的父节点开始,一层层向上找,直到HTML的body.

    dom对象.offsetWidth   获取domThe box width of the element  (width + padding + border)
    dom对象.offsetHeight  获取domThe element's box height  (height + padding + border)
</script>

clientHeight 和 offsetHeight Attributes are independent of the scrolling and position of the element.They represent the height of the element,其中:clientHeight:元素的高度,包括padding但不包括border、Horizontal scroll bar and margin. 对于内联元素,该属性始终为0,单位px,只读元素.

offsetHeight:包括padding、border、水平滚动条,但不包括margin元素的高度.对于内联元素,该属性始终为 0,单位px,只读元素.When this element's child elements are higher than this element andoverflow=scroll时,The element will scroll.此时:scrollHeight:因为子元素比父元素高,So the parent element doesn't want to be supported by the child element as high as the scroll bar is displayed.

scrollHeight 表示元素的高度,Include parts that are not currently visible.可见部分的高度其实就是clientHeight,即scrollHeight>=clientHeight总是成立的.Discussed when there are scroll barsscrollHeight才有意义,没有滚动条的时候scrollHeightclientHeight总是成立.单位px,只读元素.

scrollTop:Indicates how far the scroll bar scrolls down when there is a scroll bar,That is, the height of the covered part at the top of the element.没有滚动条时,always buildscrollTop0.单位是px,可以读取和设置.

offsetTop:The distance from the top of the current element to the top of the nearest parent element,Has nothing to do with scrollbars or not.单位px,只读元素.

client系列

  • event.clientX
    Gets the coordinate value from the left side of the viewable area of ​​the browser
  • event.clientY
    Gets the coordinate value from the upper side of the viewable area of ​​the browser
  • event.pageX
    Get the coordinate value from the left side of the document
  • event.pageY
    Get the coordinate value from the upper side of the document
  • document.documentElement.clientWidth
    获取浏览器可视区域的宽度
  • document.documentElement.clientHeight
    Gets the height of the browser's viewable area
   <script> 
     浏览器(文档)Viewable area width and height(不包含滚动条)
     console.log(document.documentElement.clientWidth);
     console.log(document.documentElement.clientHeight);

     body 元素 内容大小
     console.log(document.body.clientWidth);
     console.log(document.body.clientHeight);

     Browser viewable area width and height(包含滚动条)
     console.log(window.innerWidth);
     console.log(window.innerHeight);
    Get the coordinates of the left or upper side of the mouse's visible area of ​​the browser
    event.clientX
    event.clientY

    Get the coordinates of the mouse distance to the left or top of the document
    event.pageX
    event.pageY


    event.pageX = event.clientX + scrollLeft
    event.pageY = event.clientY + scrollTop
  </script> 

事件

  • 事件模型
    • 内联模型
      Events are written on the label 与js没有分离
    • 脚本模型
      Events are bound inside the script

      缺点:Bind the same event to the same element multiple times,The second time will overwrite the first event binding
    • DOM2级模型
  • 事件流类型
    • 事件冒泡流
      事件由最开始的元素接收,然后逐级向上传播到最不具体的那个节点(文档)
    • 事件捕获流
      事件由最最不具体的那个节点(文档)元素接收,然后逐级向下广播到最具体的那个元素
  • DOM2级事件绑定
    • dom对象.addEventListener(参数1,参数2,参数3)
      w3c 绑定事件方法
      参数1:事件名 不加on
      参数2:事件触发后调用的函数
      参数3:事件流类型 默认为false 事件冒泡流,如果为true则Capture streams for events

W3C事件处理函数 

“DOM2级事件”定义了两个方法,用于添加事件和删除事件处理程序的操作:addEventListener()和removeEventListener().所有DOM节点中都包含这两个方法,并且它们都接受3个参数;事件名、函数、冒泡或捕获的布尔值(true表示捕获,false表示冒泡).

window.addEventListener('load', function () {
    alert('Lee');
}, false);

window.addEventListener('load', function () {
    alert('Mr.Lee');
}, false);

<script>
    事件监听
    dom对象.addEventListener(参数1,参数2,参数3)
    参数1:事件名  不加on
    参数2:事件触发后调用的函数
    参数3:事件流类型  默认false 事件冒泡流  如果为true,Capture streams for events

oBtn.addEventListener("click", function () {}
</script>

移除 addEventListener() 方法添加的 "mousemove" 事件:

// 向 <div> Element adds event handler
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

// 移除 <div> The element's event handler
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);

IE事件处理函数

IE实现了与DOM中类似的两个方法:attachEvent()和detachEvent().这两个方法接受相同的参数:事件名称和函数.
When using these two sets of functions,Let's talk about the difference first:
1.IE不支持捕获,只支持冒泡;
2.IE中的this指向的是window而不是DOM对象.
3在传统事件上,IE是无法接受到event对象的,但使用了attachEvent()却可以,但有些区别.

<body>
    <button id="btn">按钮</button>
</body>
<script>
    var oBtn = document.getElementById("btn");
    // oBtn.addEventListener("click", func, true)

    // oBtn.attachEvent("onclick", func)
    // function func() {
    //     console.log("点击了按钮");
    // }

    // oBtn.removeEventListener("click", func, true);

    addEvent(oBtn, "click", function () {
        console.log("兼容了");
    });

    function addEvent(dom, type, fun) {
        try {
            dom.addEventListener(type, fun);
        } catch (err) {
            dom.attachEvent("on" + type, fun);
        }
    }
    删除事件
    dom对象.removeEventListener(参数1,参数2,参数3)
    参数1:事件名  不带on
    参数2:函数
    参数3:事件流类型  false默认 冒泡流   如果为truefor the capture stream


    oBtn.onclick = function () { }
    oBtn.onclick = null;
</script>

Keycode对照表(键码对照表) 

键码(KeyCode)对照表 - 一个工具箱 - 好用的在线工具都在这里!Online key code(KeyCode)对照表,KeyCode属性返回onkeypress事件触发的键的值的字符代码,或者 onkeydown 或 onkeyup 事件的键的代码.http://www.atoolbox.net/Tool.php?Id=815

 ev.target与this的区别

ev.target 返回的是触发事件的对象(元素)
this 返回的是绑定事件的对象(元素)

区别 :
ev.target 点击了哪个元素,就返回哪个元素
this 哪个元素绑定了这个点击事件,那么就返回谁

键盘事件属性 

  • keydown:在键盘上按下某个键时触发.如果按住某个键,会不断触发该事件,但是 Opera 浏览器不支持这种连续操作.该事件处理函数返回 false 时,会取消默认的动作(如输入的键盘字符,在 IE 和 Safari 浏览器下还会禁止keypress 事件响应).
  • keypress:按下某个键盘键并释放时触发.如果按住某个键,会不断触发该事件.该事件处理函数返回 false 时,会取消默认的动作(如输入的键盘字符).
  • keyup:释放某个键盘键时触发.该事件仅在松开键盘时触发一次,不是一个持续的响应状态.
属性说明
keyCodeThis property contains the key value of the corresponding key in the keyboard
charCodeThis property contains the corresponding keys in the keyboard Unicode 编码,仅 DOM 支持
target发生事件的节点(包含元素),仅 DOM 支持
srcElementThe element on which the event occurred,仅 IE 支持
shiftKey是否按下 Shift 键,如果按下返回 true,否则为false
ctrlKey是否按下 Ctrl 键,如果按下返回 true,否则为false
altKey是否按下 Alt 键,如果按下返回 true,否则为false
metaKey是否按下 Mtea 键,如果按下返回 true,否则为false,仅 DOM 支持

Example of a magnifying glass mask

<style>
        .box {
            position: relative;
            width: 500px;
            height: 500px;
            margin: 0 auto;
            box-shadow: 0 0 0 2px #00f;
        }

        .box .mask {
            display: none;
            position: absolute;
            left: 0;
            top: 0;
            width: 300px;
            height: 300px;
            background-color: rgba(255, 255, 0, 0.6);
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="mask"></div>
    </div>
</body>
<script>
    var oMask = document.querySelector(".box .mask");
    var oDiv = document.querySelector(".box");
    oDiv.onmouseover = function () {
        oMask.style.display = "block";
        oMask.style.cursor = "move";
        oMask.onmousemove = function (ev) {
            // console.log(ev.clientX);
            var lf = ev.clientX - oMask.offsetWidth / 2 - oDiv.offsetLeft;
            var tp = ev.clientY - oMask.offsetHeight / 2 - oDiv.offsetTop;
            if (lf <= 0) {
                lf = 0;
            }
            if (lf >= oDiv.offsetWidth - oMask.offsetWidth) {
                lf = oDiv.offsetWidth - oMask.offsetWidth;
            }

            if (tp <= 0) {
                tp = 0;
            }
            if (tp >= oDiv.offsetHeight - oMask.offsetHeight) {
                tp = oDiv.offsetHeight - oMask.offsetHeight;
            }
            oMask.style.left = lf + "px";
            oMask.style.top = tp + "px";

        }
    }

    oDiv.onmouseout = function () {
        oMask.style.display = "none";
    }


</script>

getBoundingClientRect()偏移量

与offsetLeft  offsetTop对比
offset 的方向值需要考虑到父级,如果父级是定位元素,那么子元素的offset值
相对于父元素,如果父元素不是定位元素,那么子元素的offsetThe value is relative to viewport window.
getBoundingClientRect() The value is only relative to the Visual Go window

<script>
    var oDiv = document.querySelector(".box");
    console.log(oDiv.offsetTop);

    // console.log(oDiv.getBoundingClientRect());//DOMRect {} 对象
    console.log(oDiv.getBoundingClientRect().top);//Gets the distance from the upper side of the browser's viewable area
    console.log(oDiv.getBoundingClientRect().left);//Gets the distance from the left side of the browser's viewable area
    console.log(oDiv.getBoundingClientRect().right);//Gets the distance from the right side of the element to the left side of the browser's viewable area
    console.log(oDiv.getBoundingClientRect().bottom);//Gets the distance from the lower side of the element to the upper side of the browser's viewable area
    console.log(oDiv.getBoundingClientRect().width);//获取元素宽度  盒子宽度
    console.log(oDiv.getBoundingClientRect().height);//获取元素高度  盒子高度

    oDiv.onclick = function (ev) {
        console.log(ev.clientY);
        console.log(ev.pageY);
    }
</script>

 自定义属性data

1>如何定义
规范:
i:以data开头
ii:data后必须有一个字符
建议:
i:All names are lowercase
ii:It is best not to include special symbols in the name
2>如何获取
方法:dom对象.dataset[属性名],Attribute names must use camel case.

<body>
    <div id="box" data-title="hello">hhhh</div>
</body>
<script>
    var oDiv = document.getElementById("box");

    // console.log(oDiv.dataset["title"]);


</script>

 Use custom properties to lazily load images

 <style>
        ul {
            list-style: none;
        }

        .banner {
            width: 1000px;
            height: 900px;
            margin: 0 auto;
            background-color: #ccc;
        }

        .list li {
            width: 500px;
            height: 500px;
            background: url("./img/load.gif") no-repeat center/cover;
            box-shadow: 0 0 4px rgba(0, 0, 0, .5);
        }

        .list li img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <div class="banner"></div>
    <ul class="list">
        <li><img data-src="./img/pic11.jpg" alt="" class="pic"></li>
        <li><img data-src="./img/pic22.jpg" alt="" class="pic"></li>
        <li><img data-src="./img/pic33.jpg" alt="" class="pic"></li>
        <li><img data-src="./img/pic44.jpg" alt="" class="pic"></li>
        <li><img data-src="./img/pic55.jpg" alt="" class="pic"></li>
        <li><img data-src="./img/pic66.jpg" alt="" class="pic"></li>
        <li><img data-src="./img/pic77.jpg" alt="" class="pic"></li>
    </ul>
</body>
<script>
    var oImg = document.querySelectorAll(".pic");

    window.onload = init;
    window.onscroll = throttle(init, 500);

    function init() {
        var vh = document.documentElement.clientHeight;//浏览器可视区域的高度
        // 满足某个条件  When the image enters the viewable area,Just put that picturesrcReplace with the real path
        oImg.forEach(item => {
            if (item.getBoundingClientRect().top <= vh) {
                // console.log(item.dataset["src"]);
                if (!item.src) {
                    item.src = item.dataset["src"];
                }
            }
        });
    }



    function throttle(fn, mustRun = 500) {
        const timer = null;
        let previous = null;
        return function () {
            const now = new Date();
            const context = this;
            const args = arguments;
            if (!previous) {
                previous = now;
            }
            const remaining = now - previous;
            if (mustRun && remaining >= mustRun) {
                fn.apply(context, args);
                previous = now;
            }
        }
    }
</script>

节流

<body>
    <div style="width: 100%;height:2000px;background-color:#ccc"></div>
</body>
<script>
    // 所谓的函数节流,That is, to prevent a function from executing too frequently,减少一些过快的调用来节流.
    window.onscroll = throttle(function () { console.log(111); }, 1000)

    function throttle(fn, mustRun = 500) {
        const timer = null;
        let previous = null;
        return function () {
            const now = new Date();
            const context = this;
            const args = arguments;
            if (!previous) {
                previous = now;
            }
            const remaining = now - previous;
            if (mustRun && remaining >= mustRun) {
                fn.apply(context, args);
                previous = now;
            }
        }
    }
</script>

Attach throttling、Shaking gangster website

【前端性能优化】03--JS节流、The understanding and realization of anti-shake_Ai Huanhuan's blog-CSDN博客Understand throttling​节流,Just tighten the faucet to make the water flow less,But not to stop the flow of water.Imagine in real life sometimes we need to pick up a bucket of water,I don't want to stand there and wait while I catch the water,Might have to leave for a while to do something else please,Come back when the water has almost filled the bucket,这个时候,Don't turn on the faucet too much,Otherwise, the water will be full before returning,A lot of water wasted,This is when throttling is required,Let yourself come back almost full of water.​在JSThe typical scene is,Image lazy loading monitor pagescoll事件,或者...https://blog.csdn.net/AiHuanhuan110/article/details/89225819

copyright notice
author[kind amumu],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/266/202209230621494087.html

Random recommended