我有一个绝对定位的div,其旋转变换为45度。它具有固定的高度,但宽度可以动态更改。
当我动态增加宽度时,整个元素会向右上移。
如何防止此运动使左边缘保持原位?
let box = document.getElementById('box')
let range = document.getElementById('range')
box.style.width = range.value + "px";
range.oninput = function() {
box.style.width = range.value + "px";
}
#box {
height: 100px;
top: 100px;
left: 100px;
position: absolute;
border: 1px solid black;
transform: rotate(45deg)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Resize box</title>
</head>
<body>
<div class="slidecontainer">
<input type="range" min="50" max="300" value="50" class="slider" id="range">
</div>
<div id="box"></div>
</body>
</html>
答案 0 :(得分:1)
设置transform-origin
:
let box = document.getElementById('box')
let range = document.getElementById('range')
box.style.width = range.value + "px";
range.oninput = function() {
box.style.width = range.value + "px";
}
#box {
height: 100px;
top: 100px;
left: 100px;
position: absolute;
border: 1px solid black;
transform-origin:0 0;
transform: rotate(45deg)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Resize box</title>
</head>
<body>
<div class="slidecontainer">
<input type="range" min="50" max="300" value="50" class="slider" id="range">
</div>
<div id="box"></div>
</body>
</html>