我正在尝试创建一个可以应用于 div 的函数,并让该 div 在其父级中垂直和水平居中。
我正在尝试使居中功能变得通用,这样我就不必继续重写居中代码。
使用 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)
});
最佳答案
编辑:
请参阅工作示例 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>
编辑结束
那么,将“居中”的工作委托(delegate)给它自己的函数不是可以解决问题吗?
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};
}
在你的调用函数中..
.
.
.
var obj = centerDiv($(this), $('#bThis'));
$('#bThis').css({'left':obj.cleft, 'top':obj.ctop}).fadeIn(200);
.
.
.
关于Jquery:以编程方式居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4790475/