jQuery旋转图像并相应地调整父元素

jQuery旋转图像并相应地调整父元素

本文介绍了jQuery旋转图像并相应地调整父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用css旋转来旋转图像.它工作正常,但未同时调整其他元素.它与其他元素重叠.我想要的是如果我旋转图像,则它不应与其他元素重叠,而应相应地调整其高度和宽度.请在下面查看我的代码

I am using css rotate to rotate an image. It is working fine but it is not adjusting other elements as well.It is overlapping other elements. What I want if i rotate an image then it shouldn't overlap the other elements but adjust its height and width accordingly.Please see my code below

HTML

<div id="wrapper">
<h1>Heading 1</h1>
<img id="testimg" src="http://thecutestblogontheblock.com/wp-content/uploads/2012/10/Owl-Walk-free-cute-halloween-fall-blog-BANNER.png" alt="" />
                <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<button>Rotate</button>

JQuery

var degrees = 0;
$("button").click(function(){
    degrees += 90;
        var img = $("#testimg");
        img.css({
            "-webkit-transform": "rotate(" + degrees + "deg)",
            "-moz-transform": "rotate(" + degrees + "deg)",
            "transform": "rotate(" + degrees + "deg)" /* For modern browsers(CSS3)  */
        });
});

请在JS小提琴中检查我的代码" http://jsfiddle.net/FcQZm/非常感谢您的帮助

Please check my code in JS fiddle "http://jsfiddle.net/FcQZm/"I will really appreciate your help

推荐答案

它不会自动发生,但是您可以使用getBoundingClientRect()告诉您转换后的整体高度和宽度,并使用其调整大小您的包装器(或其他元素)以适应/适应更改:

It won't happen automatically, but you can use getBoundingClientRect() to tell you what the overall height and width is after the transformation, and use that to resize your wrapper (or other elements) to fit/accommodate the change:

var angle = 0;
$(function () {
    $("button").click(function () {
        angle = (angle + 30) % 360;

        var bounds = $("img#testimg").css({
            "transform-origin": "50% 50%",
            "transform": "rotate("+angle+"deg)",
        })[0].getBoundingClientRect();

        $("#wrapper").css({
            width: bounds.width,
            height: bounds.height
        });
    });
});

演示: http://jsfiddle.net/jtbowden/pnp1kyjh/1/

(适用于最新的Firefox,Chrome,IE).

(works in latest Firefox, Chrome, IE).

这篇关于jQuery旋转图像并相应地调整父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 08:22