首页 > 解决方案 > 如何在使用 jquery 拖动元素时旋转框 div

问题描述

我知道我们需要使用transform: rotate(ndeg);才能在 CSS 中旋转特定元素。在这种情况下,我想动态地做。使用 jQuery,当用户按照用户的意愿将手柄(红色背景)拖动n度时,我想旋转盒子/容器 div 。可以在 jQuery 中使用吗?

body {
  padding: 50px;
}

.box_element {
  border: 1px solid black;
  width: 200px;
  height: 200px;
  position: relative;
  z-index: -1;
}

.handle {
  position: absolute;
  bottom: -10px;
  right: -10px;
  width: 10px;
  height: 10px;
  border: 1px solid;
  background: red;
  z-index: 10;
}
<body>
  <div class="box_element">
    THIS IS TEST
    <div class="handle"></div>
  </div>
</body>

标签: javascriptjquery

解决方案


您可以使用css 变量,然后在单击时更改变量的值。

const box_element = document.getElementById('box_element');
const handle = document.getElementById('handle');

handle.addEventListener('click', function() {
  let currentVal = getComputedStyle(box_element).getPropertyValue('--rotate_deg');

  box_element.style.setProperty(
    '--rotate_deg', ((parseInt(currentVal.replace('deg', '')) + 90) % 360) + 'deg');

});
:root {
  --rotate_deg: 0deg;
}

.box_element {
  margin: 1em;
  border: 1px solid black;
  width: 100px;
  height: 100px;
  position: relative;
  z-index: -1;
  transform: rotate(var(--rotate_deg))
}

.handle {
  position: absolute;
  bottom: -10px;
  right: -10px;
  width: 10px;
  height: 10px;
  border: 1px solid;
  background: red;
  z-index: 10;
  cursor: pointer;
}
<div class="box_element" id="box_element">
  THIS IS TEST
  <div class="handle" id="handle"></div>
</div>


推荐阅读