Here we get dynamic width of a percentage width element, and use animate()
to apply it as another element's 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>
The code above isn't working when resizing the window.
Or we can make it work when resizing the window, as long as we don't use animate()
to give it margin-left, but directly use css()
.
But this doesn't solve the problem.
How should we modify the code to solve the problem?
And also, why the code above doesn't work even after I wrote $(window).resize(testAnimate)
into code?
Use jQuery's $.offset function
var redOffset= $('.red').offset();
$('.blue').animate({
top: redOffset.top,
left: redOffset.right
});
if that doesn't work, you can try to give the .blue "position absolute" before you animate it.
$('.blue').css('position', 'absolute');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.