[英]Absolute center with jquery return margin-left 0
我已经为网站设计了一个JQuery插件,目的是使用像素而不是百分比来帮助使元素的绝对位置居中。 页面开始时,元素将垂直居中放置,而不是水平居中放置(margin-left = 0)。 当我在控制台中使用相同的脚本时,我将应用于一个元素并且它可以工作。
附加功能的代码:
$(document).ready(function() {
$(element).psfCenter();
});
功能说明
(function ($){
// center element
$.fn.psfCenter=function(orientation){
return this.each(function() {
var widthParent=$(this).parent().width()/2;
var heightParent=$(this).parent().height()/2;
var widthElement=$(this).width()/2;
var heightElement=$(this).height()/2;
var left=widthParent-widthElement;
var top=heightParent-heightElement;
console.log(orientation)
switch(orientation){
case"x":
$(this).css({
'position':'absolute',
'margin-left':left,
})
break;
case "y":
$(this).css({
'position':'absolute',
'margin-top':top
})
break;
default:
$(this).css({
'position':'absolute',
'margin-left':left,
'margin-top':top
})
break;
}
});
};
})(jQuery);
我会给元素留50%的空间,然后给边缘留出宽度的一半。 这是因为您可能希望它在较小的设备上工作(响应)。
像这样的东西: http : //jsfiddle.net/bsxqmL6f/
$.fn.psfCenter = function(orientation) { return this.each(function() { var self = $(this); var inner_width = self.width(); var inner_height = self.height(); var set_absolute = function() { self.css('position', 'absolute'); } var set_left = function() { self.css({ 'left': '50%', 'margin-left': '-' + (inner_width * .5) + 'px' }); // faster than deviding by 2 }; var set_top = function() { self.css({ 'top': '50%', 'margin-top': '-' + (inner_height * .5) + 'px' }); // faster than deviding by 2 }; set_absolute(); switch(orientation) { case 'x': set_top(); break; case 'y': set_left(); break; default: set_left(); set_top(); break; } }); } $('.center-me').psfCenter();
.center-me { width: 50px; height: 50px; background-color: red; } .huge { width: 250px; height: 250px; background-color: yellow; } .smaller { width: 120px; height: 120px; background-color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="center-me huge"></div> <div class="center-me smaller"></div> <div class="center-me"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.