【发布时间】:2021-08-12 19:26:55
【问题描述】:
我正在处理 div 内的图像 bouncing around。
这个 div 有浏览器窗口的大小。
(该 div 的大小为 100vw 和 100vh 与 CSS。)
问题:
在调整浏览器窗口变小后,图像会在 outside div 上浮动。
当我使浏览器窗口变大时,图像在碰到窗口边缘之前会弹跳。
结论:当我调整窗口大小时,图像在里面弹跳的 div 不会调整大小。
可能的解决方案:
在调整窗口大小后重新计算 CSS 关键帧(100vw 和 100vh)。
例如使浏览器窗口更大-> 框更大。使浏览器窗口更小 -> 框更小。
问题:
我能否最好地解决我的问题:
- 使用 jQuery 调整窗口大小后重新加载整个页面?
- 通过检测窗口调整大小来重置 CSS 中的
vw和vh? - ???
更新:
我刚刚尝试过的(没有运气):
$(window).resize(function() {
$(".box").css('width','100%');
$(".box").css('height','calc(100% - 160px)');
});
更新 02:
我猜我可能不得不在调整窗口大小后以某种方式重置它:
@keyframes box {
100% { transform: translateX( calc(100vw - 80px)); }
}
@keyframes smile {
100% { transform: translateY( calc(100vh - 160px)); }
}
我希望我可以让框流畅地跟随浏览器窗口的宽度和高度...
更新 03:
正如“A Haworth”在下面的 cmets 中指出的那样,此问题仅发生在 Safari 中,而不发生在 Chrome 中。
更新 04
我目前正在使用“A Haworth”的临时解决方案,并且仅在用户使用 Safari 时重新加载窗口调整大小时的动画。
const box = document.querySelector('.box');
const smile = document.querySelector('.smile');
if (
navigator.userAgent.indexOf('Safari') != -1 &&
navigator.userAgent.indexOf('Chrome') == -1 &&
navigator.userAgent.indexOf('CriOS/') == -1
) {
function resize() {
box.style.animationName = 'none';
smile.style.animationName = 'none';
$('.smile').hide();
setTimeout(function () {
box.style.animationName = 'box';
smile.style.animationName = 'smile';
$('.smile').fadeIn('slow');
}, 1000);
}
window.onresize = resize;
}
片段:
body {
overflow: hidden;
padding: 0;
margin: 0;
}
.box {
position: absolute;
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 0;
margin: 0;
}
.smile {
height: 80px;
width: 80px;
margin: 0;
padding: 0;
}
.box {
animation: box 13s linear infinite alternate;
}
.smile {
animation: smile 7s linear infinite alternate;
}
@keyframes box {
100% {
transform: translateX( calc(100vw - 80px));
}
}
@keyframes smile {
100% {
transform: translateY( calc(100vh - 80px));
}
}
<div class="box">
<img class="smile" src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/apple/285/smiling-face-with-sunglasses_1f60e.png" />
</div>
【问题讨论】:
-
你的例子很奇怪:为什么盒子的大小会在动画期间发生变化和平移?这是故意的吗?
标签: jquery css css-animations