gpt4 book ai didi

javascript - jQuery : How to use percentage width of one element as a value to animate another element, 并确保即使在调整窗口大小时它也能正常工作?

转载 作者:行者123 更新时间:2023-11-28 07:05:07 26 4
gpt4 key购买 nike

这里我们获取百分比宽度元素的动态宽度,并使用 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 的 $.offset功能

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

如果这不起作用,您可以在设置动画之前尝试为 .blue 赋予“绝对位置”。

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

关于javascript - jQuery : How to use percentage width of one element as a value to animate another element, 并确保即使在调整窗口大小时它也能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com