我即将以更具体的方式进入 jQuery 世界,因此我编写了一个函数,通过根据子级和父级的 outerWidth 设置 css left 属性,将绝对定位的 anchor 元素居中放置在相对定位的 div 中。
这里是:
$.fn.moreCenter = function() {
var sblockWidth = $(this).outerWidth();
var moreWidth = $(this).children('a').outerWidth();
var moreLeft = (sblockWidth - moreWidth)/2;
$(this).children('a').css('left', moreLeft + 'px');
};
然后我按类定位父 div:
$(document).ready(function() {
$('.single-block').moreCenter();
});
重点是.single-block结构在页面的很多地方重复出现,每个.single-block的宽度可能不一样。这就是函数使用 (this) 泛化父 div 的原因。
但是,该函数似乎对每个“.single-block a”元素应用相同的左值,根据它找到的第一个 .single-block 计算,而不是为每个元素重新计算它。
代码有什么问题?
最佳答案
SonnyPrince 转换/翻译在旧版浏览器中不起作用。
感谢 Paulie_D,我能够以这种方式通过 css 将子 anchor 元素居中。
parent { position: relative;
width: can be expressed in %;
whateverprop: whoteverset; }
child { position: absolute;
left: 0;
right: 0;
margin: 0 auto; }
无论如何,我什至设法通过使用 .each() 更正了上面的 jQuery 函数。
$.fn.moreCenter = function() {
$(this).each(function() {
var sblockWidth = $(this).outerWidth();
var moreWidth = $(this).children('a').outerWidth();
var moreLeft = (sblockWidth - moreWidth)/2;
$(this).children('a').css('left', moreLeft + 'px');
});
};
我的问题已经解决了,谢谢大家:)
关于jquery - 在不同宽度的同级父元素中居中子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034170/