簡體   English   中英

帶有jQuery的絕對中心返回左邊距為0

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM