Programing

jQuery를 사용하여 패딩 또는 여백 값을 정수로 픽셀 단위로 표시

lottogame 2020. 5. 7. 07:54
반응형

jQuery를 사용하여 패딩 또는 여백 값을 정수로 픽셀 단위로 표시


jQuery에는 높이 또는 너비를 픽셀 단위로 정수로 반환하는 height () en width () 함수가 있습니다 ...

jQuery를 사용하여 요소의 패딩 또는 여백 값을 픽셀 단위 및 정수로 얻는 방법은 무엇입니까?

내 첫 번째 아이디어는 다음을 수행하는 것이 었습니다.

var padding = parseInt(jQuery("myId").css("padding-top"));

그러나 예를 들어 패딩이 ems로 주어지면 어떻게 픽셀 단위로 값을 얻을 수 있습니까?


Chris Pebble이 제안한 JSizes 플러그인을 살펴보면 내 버전이 올바른 것임을 깨달았습니다. :). jQuery는 항상 값을 픽셀 단위로 반환하므로 정수로 파싱하는 것이 해결책이었습니다.

Chris Pebble과 Ian Robinson 덕분에


CSS를 사용할 수 있어야합니다 ( http://docs.jquery.com/CSS/css#name ). "padding-left"또는 "margin-top"과 같이 더 구체적이어야 할 수도 있습니다.

예:

CSS

a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}

JS

$("a").css("margin-top");

결과는 10px입니다.

정수 값을 얻으려면 다음을 수행하십시오.

parseInt($("a").css("margin-top"))

외부와 내부 높이 / 너비를 비교하여 총 여백과 패딩을 얻습니다.

var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());

parseInt 함수에는 변환에 사용 된 숫자 시스템을 정의하는 "radix"매개 변수가 있으므로 호출 parseInt(jQuery('#something').css('margin-left'), 10);하면 왼쪽 여백이 정수로 리턴됩니다.

이것이 JSizes가 사용하는 것입니다.


이미 기본적으로 제공되는 작업을 수행하기 위해 다른 라이브러리를로드하지 마십시오!

jQuery .css()는 %와 em을 픽셀과 동등한 것으로 변환하고 반환 된 문자열의 끝에서 parseInt()를 제거하고 'px'정수로 변환합니다.

http://jsfiddle.net/BXnXJ/

$(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

주변 치수를 얻는 방법은 다음과 같습니다.

var elem = $('#myId');

var marginTopBottom  = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight  = elem.outerWidth(true)  - elem.outerWidth();

var borderTopBottom  = elem.outerHeight() - elem.innerHeight();
var borderLeftRight  = elem.outerWidth()  - elem.innerWidth();

var paddingTopBottom  = elem.innerHeight() - elem.height();
var paddingLeftRight  = elem.innerWidth()  - elem.width();

Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)


This simple function will do it:

$.fn.pixels = function(property) {
    return parseInt(this.css(property).slice(0,-2));
};

Usage:

var padding = $('#myId').pixels('paddingTop');

Parse int

parseInt(canvas.css("margin-left")); 

returns 0 for 0px


You can just grab them as with any CSS attribute:

alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));

You can set them with a second attribute in the css method:

$("#mybox").css("padding-right", "20px");

EDIT: If you need just the pixel value, use parseInt(val, 10):

parseInt($("#mybox").css("padding-right", "20px"), 10);

ok just to answer the original question:

you can get the padding as a usable integer like this:

var padding = parseInt($("myId").css("padding-top").replace("ems",""));

If you have defined another measurement like px just replace "ems" with "px". parseInt interprets the stringpart as a wrong value so its important to replace it with ... nothing.


You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top

Don't use string.replace("px", ""));

Use parseInt or parseFloat!


I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...


Shamelessly adopted from Quickredfox.

jQuersy.fn.cssNum = function(){
    return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};

update

Changed to parseInt(val, 10) since it is faster than parseFloat.

http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/20


Not to necro but I made this which can determine pixels based on a variety of values:

$.fn.extend({
  pixels: function (property, base) {
    var value = $(this).css(property);
    var original = value;
    var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1 
      ? $(this).parent().outerWidth()
      : $(this).parent().outerHeight();

    // EM Conversion Factor
    base = base || 16;

    if (value == 'auto' || value == 'inherit') 
        return outer || 0;

    value = value.replace('rem', '');
    value = value.replace('em', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? base * value : 0;
    }

    value = value.replace('pt', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? value * 1.333333 : 0; // 1pt = 1.333px
    }

    value = value.replace('%', '');

    if (value !== original) {
      value = parseFloat(value);
      return value ? (outer * value / 100) : 0;
    }

    value = value.replace('px', '');
    return parseFloat(value) || 0;
  }
});

This way, we take into account for sizing, and auto / inherit.

참고URL : https://stackoverflow.com/questions/590602/padding-or-margin-value-in-pixels-as-integer-using-jquery

반응형