javascript 如何用js修改css转换

but5z9lq  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(124)

我需要添加平移到一些元素,问题是他们中的一些已经有旋转。我试图修改我的转换矩阵,但有时它有6有时16个元素。计划是translateX的项目宽度的一半。

var page = $("<div>");
this.pages.push(page);
page.css({                
            "-webkit-transform": "rotateY(180deg)",
            "-webkit-transition-duration": "0.5s"
        });            
for (var i = 0; i < this.pages.length; i++) {
        var matrix = this.pages[i].css("transform");

        if (matrix != "none")
            matrix = matrix.replace(/[^0-9\-.,]/g, '').split(',');
        else
            matrix = [ 1, 0, 0, 0, 1, 0 ];
        var index = matrix.length == 16 ? 3  : 2;            
        matrix[index] = -0.5;                
        this.pages[i].css({ "transform": "matrix(" + matrix.join(",") + ")" });
        }
vcirk6k6

vcirk6k61#

以下是代码的工作版本,其中仅做了一些更改:

  • 不要使用-webkit-前缀来进行转换,十年来,每个浏览器都不带前缀地支持transform
  • 在jQuery中,已经有了返回给您的元素的可迭代集合,不需要尝试创建单独的“pages”数组。
  • 在jQuery集合上循环时,最好使用内置的jQuery each()方法,而不是for循环。只需向它传递一个函数,该函数将在集合中的每个对象上运行。该函数将被传递一个索引和this元素。
  • 我认为使用slice从矩阵中获取值比使用正则表达式要容易得多,也更容易推理出你要完成的任务。

对工作片段进行了进一步注解:

const $pages = $("div"); /* this is already iterable */
$pages.each(addTranslateY); /* using jQuery's each method */

function addTranslateY(i) {
  /* get the current transform values */
  const transformMatrix = $(this).css("transform");
  /* get the width in pixels */
  const width = $(this).width();
  /* create an array from the string matrix values */
  const transformArray =
    transformMatrix === "none"
      ? [1, 0, 0, 1, 0, 0]
      : transformMatrix
          .slice(7, -1) /* get just the values in the parens */
          .split(", ") /* split the string into an array */
          .map(Number); /* convert each value into a number */

  /* change the f value of the matrix */
  transformArray[5] += width / 2;

  /* update the element with the new matrix */
  $(this).css("transform", `matrix(${transformArray.join(", ")})`);
}

/*
  transformArray values:
  a represents scale x [0]
  b represents skew x [1]
  c represents skew y [2]
  d represents scale y [3]
  e represents translate x [4]
  f represents translate y [5]
*/
div {
  background-color: deeppink;
  height: var(--size, 3rem);
  width: var(--size, 3rem);
  margin: 1rem;
}

.rotate {
  transform: rotate(30deg);
  background-color: blue;
}

.skew {
  transform: skew(30deg);
  background-color: orange;
}

.scale {
  transform: scale(0.5);
  background-color: yellowgreen;
}

.translate {
  transform: translate(100px, -50px);
  background-color: red;
}
<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<div></div>
<div class="rotate" style="--size: 3rem"></div>
<div class="skew" style="--size: 2rem"></div>
<div class="scale" style="--size: 6rem"></div>
<div class="translate" style="--size: 5rem"></div>

相关问题