Get the value of transform offset by regularization

Time:2021-5-11

Offsetwidth gets the width of the element
Offsetleft gets the element positioning offset value
When an element is offset by transform (translatex: 100px) in CSS3, offset left cannot be used to get the offset value
terms of settlement:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
<div class="box">
</div>
< button class = "BTN" > button < / button >
< button class = "btn2" > button 2 < / button >
<script>
    var box = document.querySelector(".box");
    var boxwidth = box.offsetWidth;
    console.log(boxwidth); //  The width of the box is 200
    var btn = document.querySelector(".btn");
    var btn2 = document.querySelector(".btn2");
    //Click the button to move the box. A negative value means that the amount of left movement is 100
    btn.onclick = function () {
        box.style.transform = "translateX(-100px)";
        box.style.webkitTransform = "translateX(-100px)";
    };
    //Click button 2 to print out the moving value
    btn2.onclick = function () {
        console.log(box.offsetLeft); //  The default offset is 8
        var x = box.style.transform || box.style.webkitTransform;
        console.log(x); // translateX(-100px)
        var reg = /(translateX\(-)(\d+)(px\))/; //  There is a regular difference between left shift and right shift- 
        var result = reg.exec(x)[2]; 
        console.log(result); //  Get the moving value of 100 through regularization
    }
</script>
</body>
</html>