問題描述
如果你看看:http://jsfiddle.net/KA4dz/
在這個演示中,您可以清楚地看到內部元素由于其旋轉而延伸到外部元素之外.請求是縮小內部元素(同時保持縱橫比和中心位置),使其適合其容器.
In this demo, you can clearly see the inner element reaching outside of the outer element due to its rotation. The request is to scale down the inner element (while maintaining aspect ratio's and center positioning) just so it fits within its container.
用例是用戶可以手動旋轉這樣的內部元素,同時確保它留在外部元素內.(所以簡單地縮小直到適合眼睛不是解決方案).
The use-case is that the user can manually rotate such an inner element while ensuring that it stays within the outer element. (so simply scaling down until it fits for the eyes is not a solution).
這是我的數學技能明顯缺乏的情況.在這個階段發布我嘗試過的內容不會有多大好處.有人能指出我正確的方向嗎?
This is a scenario where my math skills are clearly lacking. Posting what I've tried wont do much good at this stage. Can someone point me in the right direction?
謝謝!
另一個要求是內部元素僅在需要時縮小,而在不需要時從不縮小(需要時意味著離開外部元素的邊界)
One additional requirement is that the inner element only scales down whenever its required but never scales down when its not required (where required means leaving the boundaries of the outer element)
保存點擊:
.outer{
border: 1px solid black;
width: 100px;
height: 50px;
margin: 100px;
}
.inner{
background: blue;
width: 100px;
height: 50px;
transform: rotate(-40deg);
-webkit-transform: rotate(-40deg);
}
<div class="outer">
<div class="inner">
</div>
</div>
推薦答案
這很有趣.這是我的解決方案:http://jsfiddle.net/fletiv/jrHTe/
This was interesting. Here's my solution: http://jsfiddle.net/fletiv/jrHTe/
而 javascript 看起來像這樣:
And javascript looks like this:
(function () {
var setRotator = (function () {
var setRotation,
setScale,
offsetAngle,
originalHeight,
originalFactor;
setRotation = function (degrees, scale, element) {
element.style.webkitTransform = 'rotate(' + degrees + 'deg) scale(' + scale + ')';
element.style.transform = 'rotate(' + degrees + 'deg) scale(' + scale + ')';
};
getScale = function (degrees) {
var radians = degrees * Math.PI / 180,
sum;
if (degrees < 90) {
sum = radians - offsetAngle;
} else if (degrees < 180) {
sum = radians + offsetAngle;
} else if (degrees < 270) {
sum = radians - offsetAngle;
} else {
sum = radians + offsetAngle;
}
return (originalHeight / Math.cos(sum)) / originalFactor;
};
return function (inner) {
offsetAngle = Math.atan(inner.offsetWidth / inner.offsetHeight);
originalHeight = inner.offsetHeight;
originalFactor = Math.sqrt(Math.pow(inner.offsetHeight, 2) + Math.pow(inner.offsetWidth, 2));
return {
rotate: function (degrees) {
setRotation (degrees, getScale(degrees), inner);
}
}
};
}());
var outer = document.getElementById('outer'),
inner = document.getElementById('inner'),
rotator = setRotator(inner),
degrees = 0;
window.setInterval(function () {
degrees += 1;
if (degrees >= 360) {
degrees = 0;
}
rotator.rotate(degrees);
}, 50);
}());
這是一張試圖解釋我的代碼邏輯的圖像.:)
Here's an image which tries to explain the logic of my code. :)
這篇關于CSS 在容器內旋轉元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!