복붙노트

[JQUERY] jQuery를에서 CSS 규칙의 백분율 값을 얻을

JQUERY

jQuery를에서 CSS 규칙의 백분율 값을 얻을

해결법


  1. 1.어떤이 내장되지-에있어 방법, 난 두려워. 당신이 뭔가를 할 수 있습니다 :

    어떤이 내장되지-에있어 방법, 난 두려워. 당신이 뭔가를 할 수 있습니다 :

    var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';
    

  2. 2.가장 쉬운 방법

    가장 쉬운 방법

    $('.largeField')[0].style.width
    
    // >>> "65%"
    

  3. 3.이것은 대부분의 확실히 가능하다!

    이것은 대부분의 확실히 가능하다!

    당신은 반드시 먼저 숨기기 () 부모 요소입니다. 이 자식 요소에 대해 픽셀을 계산에서 자바 스크립트를 방지 할 수 있습니다.

    $('.parent').hide();
    var width = $('.child').width();
    $('.parent').show();
    alert(width);
    

    내 예를 참조하십시오.

    나는이 해킹을 발견하는 첫 번째 해요 경우 지금 ... 궁금 :)

    최신 정보:

    element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');
    

    그것은 당신이 .remove 할 수있는 태그, 전에 숨겨진 요소 뒤에 떠날 것이다 ().

    한 줄의 예를 참조하십시오.

    더 나은 아이디어에 열려있어!


  4. 4.당신은 document.styleSheets 개체에 액세스 할 수 있습니다 :

    당신은 document.styleSheets 개체에 액세스 할 수 있습니다 :

    <style type="text/css">
        .largeField {
            width: 65%;
        }
    </style>
    <script type="text/javascript">
        var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
        for (var i=0; i < rules.length; i++) {
            var rule = rules[i];
            if (rule.selectorText.toLowerCase() == ".largefield") {
                alert(rule.style.getPropertyValue("width"));
            }
        }
    </script>
    

  5. 5.CSS의 스타일이 비율이 포함 된 경우 늦은하지만, 새로운 사용자를 위해,이 시도 :

    CSS의 스타일이 비율이 포함 된 경우 늦은하지만, 새로운 사용자를 위해,이 시도 :

    $element.prop('style')['width'];
    

  6. 6.JQuery와는 아담스의 답변에 따라 플러그인이 :

    JQuery와는 아담스의 답변에 따라 플러그인이 :

    (function ($) {
    
        $.fn.getWidthInPercent = function () {
            var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
            return Math.round(100*width)+'%';
        };
    
    })(jQuery);
    
    $('body').html($('.largeField').getWidthInPercent());​​​​​
    

    '65 % '를 반환합니다. 당신이 (폭 == '65 %')의 경우처럼 할 경우에만 더 나은 작업에 둥근 번호를 반환합니다. 당신이 일을하지 않았 직접 아담스 응답을 사용했을 경우 (내가 64.93288590604027 같은 것을 얻었다). :)


  7. 7.timofey의 우수하고 놀라운 솔루션을 구축, 여기에 순수 자바 스크립트 구현은 다음과 같습니다

    timofey의 우수하고 놀라운 솔루션을 구축, 여기에 순수 자바 스크립트 구현은 다음과 같습니다

    function cssDimensions(element)
      var cn = element.cloneNode();
      var div = document.createElement('div');
      div.appendChild(cn);
      div.style.display = 'none';
      document.body.appendChild(div);
      var cs = window.getComputedStyle
        ? getComputedStyle(cn, null)
        : cn.currentStyle;
      var ret = { width: cs.width, height: cs.height };
      document.body.removeChild(div);
      return ret;
    }
    

    누군가에게 도움이 바랍니다.


  8. 8.내가 jQuery를 글로벌 스타일 시트의 값을 얻기에 비슷한 문제가, 결국 나는 상기와 같은 솔루션을 함께했다.

    내가 jQuery를 글로벌 스타일 시트의 값을 얻기에 비슷한 문제가, 결국 나는 상기와 같은 솔루션을 함께했다.

    그냥 다른 사람들이 나중에 발견 혜택을 누릴 수 있도록 두 가지 질문을 가교 싶었다.


  9. 9.교차 곱셈을 사용하는 비율 픽셀로 변환합니다.

    교차 곱셈을 사용하는 비율 픽셀로 변환합니다.

    수식 설정 :

    1.) (element_width_pixels / parent_width_pixels) = (element_width_percentage / 100)

    2) = element_width_percentage (100 * element_width_pixels) / parent_width_pixels

    실제 코드 :

    <script>
    
       var $width_percentage = (100 * $("#child").width()) / $("#parent").width();
    
    </script>
    

  10. 10.당신은 당신이 중 하나에 jQuery로 액세스해야 스타일을 넣을 수 있습니다 :

    당신은 당신이 중 하나에 jQuery로 액세스해야 스타일을 넣을 수 있습니다 :

    그 다음은 JS 문서 헤드의 스타일 태그 내에서 구문 분석 모두에 기능을 작성하고 당신이 필요로하는 값을 반환 (반드시 용이하지만) 가능해야한다.


  11. 11.심지어 자바 스크립트에서 간단한 jQuery를 아무것도, 아무것도가 없습니다. timofey의 답변을 복용하고 그것을 실행, 난 당신이 원하는 특성을 얻을 작동이 기능을 생성 :

    심지어 자바 스크립트에서 간단한 jQuery를 아무것도, 아무것도가 없습니다. timofey의 답변을 복용하고 그것을 실행, 난 당신이 원하는 특성을 얻을 작동이 기능을 생성 :

    // gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
    // domNode - the node to get properties for 
    // properties - Can be a single property to fetch or an array of properties to fetch
    function getFinalStyle(domNode, properties) {
        if(!(properties instanceof Array)) properties = [properties]
    
        var parent = domNode.parentNode
        if(parent) {
            var originalDisplay = parent.style.display
            parent.style.display = 'none'
        }
        var computedStyles = getComputedStyle(domNode)
    
        var result = {}
        properties.forEach(function(prop) {
            result[prop] = computedStyles[prop]
        })
    
        if(parent) {
            parent.style.display = originalDisplay
        }
    
        return result
    }
    

  12. 12.당신은 요소의 현재 폭을 반환하는 CSS (폭) 기능을 사용할 수 있습니다.

    당신은 요소의 현재 폭을 반환하는 CSS (폭) 기능을 사용할 수 있습니다.

    즉.

    var myWidth = $("#myElement").css("width");
    

    또한보십시오: http://api.jquery.com/width/ http://api.jquery.com/css/

  13. from https://stackoverflow.com/questions/744319/get-css-rules-percentage-value-in-jquery by cc-by-sa and MIT license