Jquery element width
I've made a function in order to center-align a submit button in forms :
function btnCentrage(element, parent){
var widthForm = $(parent).innerWidth();
var widthBtn = $(element).outerWidth();
var placement = (widthForm - widthBtn) / 2;
console.log(element + '/' + parent + '/' + widthForm + '/' + widthBtn + '/' + placement);
$(element).css('margin', '0 '+ placement + 'px');
}
btnCentrage('#connectForm .btn_small', '.connect_bottom');
When I call this function (after DOM loading), it doesn't have any element width or parent wi开发者_如何学编程dth.
In JQuery you just use width()
.
As explained here, you can just do:
var widthBtn = $(element).width();
The most obvious reason that would be the case is that it's not finding the element or parent. Try adding $(parent).length
and $(element).length
to your console.log
debug dump so you see whether it's actually locating your DOM nodes.
Your code appears to work so the answer is that the elements are either not being selected correctly (as Ianus says) or your elements are not visible as Shankar says.
And as was also pointed out you can easily use CSS to do this.
Your code: http://jsfiddle.net/kasdega/QbvxA/
One possible CSS Version: http://jsfiddle.net/kasdega/QbvxA/1/
精彩评论