javascript 使用 JQuery 将 Div 的背景图像旋转 90 度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24842026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rotate Background Image of Div 90 Degrees using JQuery
提问by scientiffic
I have a div that looks something like this:
我有一个看起来像这样的 div:
<p class="stepNode" aria-disabled="true" style="background: url(https://...jpg) 50% 50%;">
<p class="stepLabel">
<div> New Step</div>
</p>
</p>
I want to rotate the background image within the div 90 degrees counterclockwise (without rotating the entire container ".stepNode". How can I do this using jQuery?
我想将 div 内的背景图像逆时针旋转 90 度(不旋转整个容器“.stepNode”。 如何使用 jQuery 执行此操作?
采纳答案by Yatoom
You can add a :before to a container which contains the background (See thisfor more information).
您可以将 :before 添加到包含背景的容器中(有关更多信息,请参阅此内容)。
.stepNode:before {
content: "";
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(some-background-url-here) 40% 50% no-repeat;
Then you make a css class that contains the rotate properties.
然后创建一个包含旋转属性的 css 类。
.transform:before {
-webkit-transform: rotate(-30deg);
-moz-transform: rotate(-30deg);
-ms-transform: rotate(-30deg);
-o-transform: rotate(-30deg);
transform: rotate(-30deg);
}
And via jquery, you can add the class:
通过 jquery,您可以添加类:
$(".stepNode").addClass("transform");
Also, you can set a transition time, to add animation (put this in .stepNode:before)
此外,您可以设置过渡时间,以添加动画(将其放在 .stepNode:before 中)
-webkit-transition: all 1s;
-moz-transition: all 1s;
-ms-transition: all 1s
-o-transition: all 1s;
transition: all 1s;
Here is a working jsfiddle.
这是一个有效的jsfiddle。
Edit: 90 degrees version: jsfiddle
编辑:90度版本:jsfiddle
回答by IndieRok
In order to achieve this, you would need to have two divs which are in absolute positioning. In containing the background image and one containing the text.
为了实现这一点,您需要有两个绝对定位的 div。在包含背景图像和一个包含文本。
<div class="myRotate"></div>
<div class="myContent">
<p class="stepNode" aria-disabled="true">
<p class="stepLabel">
<div> New Step</div>
</p>
</p>
</div>
Next you could attach a Jquery OnClick event on whatever element you want in order for the background to rotate.
接下来,您可以在您想要的任何元素上附加一个 Jquery OnClick 事件,以便背景旋转。
$(function(){
$('.myContent').click(function(){
$('.myRotate').css({'-webkit-transform' : 'rotate(-90deg)',
'-moz-transform' : 'rotate(-90deg)',
'-ms-transform' : 'rotate(-90deg)',
'transform' : 'rotate(-90deg)'});
});
});
Here is a working example
这是一个工作示例