使用 JavaScript 旋转图像
旋转 HTML 元素是使用 CSS 执行的常见要求。CSS 提供了一个转换属性,你可以使用它来完成此任务。在本文中,我们将学习如何使用 JavaScript 旋转图像。
使用 CSS 转换使用 JavaScript 旋转图像
CSS 变换属性允许你旋转、缩放、倾斜或移动元素。改变 CSS 视觉格式模型的坐标空间。如果属性的值不是 none,则创建堆栈上下文。在这种情况下,元素充当容器块,其位置根据其包含的元素设置为 position: fixed
或 position: absolute
。
转换属性可以指定为 none
关键字或一个或多个 transform
函数。如果 perspective()
是几个函数值之一,它必须首先出现。
语法:
transform: none;
transform: translateX($Xpx) rotate($Ydeg) translateY($Zpx);
当要应用一个或多个 CSS 变换函数时,变换值是 transform-function
。变换函数从左到右相乘。从右到左的复合,有效地应用了变换。在上面的语法中,我们使用 translateX
,它水平翻译具有特定像素的元素,translateY
,它垂直翻译具有特定像素的元素,以及 rotate
,它围绕一个特定角度旋转元素二维平面上的固定点。
none
表示不应应用任何转换。有关详细信息,请参阅 transform 文档。
<input id="button" type="button" value="Rotate">
<div id="img_container">
<img src="https://www.google.com/images/srpr/logo3w.png" id="image">
<div>
let angle = 0, img = document.getElementById('img_container');
document.getElementById('button').onclick = function() {
angle = (angle + 90) % 360;
img.className = 'rotate' + angle;
}
#img_container.rotate90 {
width: 100px;
height: 820px
}
#image {
transform-origin: top left;
-webkit-transform-origin: top left;
}
#img_container.rotate90 #image {
transform: rotate(90deg) translateY(-100%);
-webkit-transform: rotate(90deg) translateY(-100%);
}
在上面的代码中,我们创建了一个容器,每次用户点击旋转按钮时,我们将当前角度加 90 度,取 360 度的模数。一旦找到最终角度,我们就可以添加其属性已使用 CSS 声明的预定义类。
该示例仅显示 90 度旋转,但你可以将其定义为任何角度,例如 45 度或 105 度等。上面代码的输出如下所示:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。