jQuery:如何使用一个元素的百分比宽度作为动画另一个元素的值,并确保它的工作,即使在调整窗口的大小

jQuery: How to use percentage width of one element as a value to animate another element, and make sure it works even when resizing the window?

本文关键字:元素 工作 确保 窗口 调整 另一个 何使用 一个 jQuery 百分比 动画      更新时间:2023-09-26

这里我们得到一个percentage width元素的动态宽度,并使用animate()将其应用于另一个元素的margin-left。

function testAnimate() {
	var redWidth = $('.red').width();
	$('.blue').animate({marginLeft: "0px"}, 800).delay(3000);
	$('.blue').animate({marginLeft: redWidth}, 800, testAnimate).delay(3000);
}
	
$(document).ready(testAnimate);
$(window).resize(testAnimate);
.red{
	background-color: red;
        width: 40%;
	height: 200px;
}
.blue{
	background-color: blue;
	width: 100px;
	height: 200px;
}
<div class="red"></div>
<div class="blue"></div>

上面的代码在调整窗口大小时不起作用。
或者我们可以让它在调整窗口大小时工作,只要我们不使用animate()给它左边框,而是直接使用css()
但这并不能解决问题。

我们应该如何修改代码来解决这个问题?
还有,为什么上面的代码不工作,甚至在我把$(window).resize(testAnimate)写入代码后?

使用jQuery的$。偏移函数

var redOffset= $('.red').offset();
$('.blue').animate({
   top: redOffset.top,
   left: redOffset.right
});

如果这不起作用,你可以尝试在制作动画之前给它添加。blue "position absolute"。

$('.blue').css('position', 'absolute');