Jquery: programmatically center elements
I'm trying to create a function that I can apply to a div, and have that div centered within it's parent, both vertically and horizontally.
I'm trying to make the function of centering things generic so i don't have to keep rewriting the centering piece of code.
What would you do to make centering things easiest, WITH JQUERY.
$('p').hoverIntent(function () {
var myObject = $('#bThis')
var Ctop = $(this).offset().top + ($(this).height() / 2) - (myObject.outerHeight() / 2)
var Cleft = $(this).offset().left + ($(this).width() / 2) - (myObject.outerWidth() / 2)
if (开发者_如何学运维$('#placeB').hasClass('place')) {
$(this).animate({color: "#999999", backgroundColor: "#f5f5f5"}, 400)
$('#bThis').css({'left':Cleft, 'top':Ctop}).fadeIn(200)
}
}, function() {
$(this).stop().animate({color: "#333", backgroundColor: "#fff"}, 200)
$('#bThis').fadeOut(200)
});
EDIT:
See the working example here.
<div id="container">
<div id="element">
</div>
</div>
<style>
#container{
height:100px;
width:100px;
border:1px solid #000;
background:#EEE;
position:relative;
}
#element{
height:50px;
width:50px;
border:1px solid #000;
background:#333;
position:relative;
}
<style>
<script>
function centerDiv(element, xPosFromCenter, yPosFromCenter){
var xPos = parseInt(element.parent().css('width'))/2 -parseInt(element.css('width'))/2 - xPosFromCenter;
var yPos = parseInt(element.parent().css('height'))/2 -parseInt(element.css('height'))/2 - yPosFromCenter;
element.css({top: yPos, left:xPos});
}
$().ready(function(){
centerDiv($('#element'), 0, 0);
});
<script>
End of Edit
Well, wouldn't delegating the job of "center-ing" to its own function do the trick?
function centerDiv(element, parent){
var Ctop = $(element).offset().top + ($(element).height() / 2) - (parent.outerHeight() / 2)
var Cleft = $(element).offset().left + ($(element).width() / 2) - (parent.outerWidth() / 2)
return {ctop: Ctop, cleft:Cleft};
}
In your calling function..
.
.
.
var obj = centerDiv($(this), $('#bThis'));
$('#bThis').css({'left':obj.cleft, 'top':obj.ctop}).fadeIn(200);
.
.
.
精彩评论