gpt4 book ai didi

jquery - div 以 jQuery 为中心

转载 作者:行者123 更新时间:2023-12-01 05:53:52 25 4
gpt4 key购买 nike

我有这段 jQuery 代码,它将 div 置于其父级的中心。

$(document).ready(function(){
function move_div(){
parent_width = $('.holder').parent().width();
parent_height = $('.holder').parent().height();

obj_width = $('.holder').width();
obj_height = $('.holder').height();

$('.holder').css('top', (parent_height / 2) - (obj_height / 2)).css('left', (parent_width / 2) - (obj_width / 2));
}
move_div();

$(window).resize(function(){
move_div();
});
});

我想在多个 div 上使用它,但不能,因为代码只获取带有“holder”类的第一个 div 的高度 + 宽度...任何人都可以帮助解决这个问题...?

最佳答案

使用.each()逐一循环遍历所有元素。

$(this) 引用类 holder 的当前元素

$(document).ready(function () {
function move_div() {
$('.holder').each(function () {
parent_width = $(this).parent().width();
parent_height = $(this).parent().height();

obj_width = $(this).width();
obj_height = $(this).height();
$(this).css('top', (parent_height / 2) - (obj_height / 2)).css('left', (parent_width / 2) - (obj_width / 2));
});
}
move_div();
$(window).resize(function () {
move_div();
});
});

关于jquery - div 以 jQuery 为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236188/

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