2013-04-18 3 views
9

jquery를 사용하여 요소의 너비를 10rem만큼 늘릴 수있는 방법은 무엇입니까? 문제는 Jquery가 항상 너비/높이를 픽셀 단위로 반환하므로 다른 단위에서 높이/너비를 업데이트하려고합니다.jquery를 사용하여 컨테이너의 너비를 10만큼 늘립니다.

예에 : JS Bin

var $c = $('#container'); 
console.log($c.width()); 

var c = document.getElementById('container'); 

// Q1. Why is it different from above one. This is 324 while earlier it was 320. See the output. 
console.log(c.clientWidth); 

// Q2. How to update the code to increase the width by 10rem. 
$c.css({width: $c.width() + 10}); //It adds 10 pixels here. 

console.log($c.width()); 

내 질문은 코드에 주석이다.

+2

귀하의 질문에 동의하지만 rem' 단위 ** 글꼴을위한'생각은 참조 : _HTTP : //www.w3.org/TR/css3 -values ​​/ _ –

+0

그래도 괜찮아 요. 장치 크기에 따라 페이지 내용을 맞출 수 있기 때문에 em/rem 단위가 꽤 많이 사용됩니다. 글꼴 크기가 변경되면 그에 따라 다른 모든 내용이 변경됩니다. – sachinjain024

답변

12

내가 html 요소의 font-size을 복용하는 함수를 사용하여, 당신에게 rem을 줄 것이라고 생각, 당신은 변경 되어도를 검색 할 수 있습니다 :

// This Function will always return the initial font-size of the html element 
    var rem = function rem() { 
     var html = document.getElementsByTagName('html')[0]; 

     return function() { 
      return parseInt(window.getComputedStyle(html)['fontSize']); 
     } 
    }(); 

// This function will convert pixel to rem 
    function toRem(length) { 
     return (parseInt(length)/rem()); 
    } 

예 : http://jsfiddle.net/4NkSu/1/

+1

@xpy를 멋지게 처리했습니다. 나는 거기에 우아한/간단한 해결책이 존재해야한다고 생각했다. 너의 것은 너무 좋다 :) – sachinjain024

6

jquery를 사용하여 업데이트 된 답변을 게시하기로 결정했습니다. 매개 변수없이 함수를 호출하여 한 번의 rem에서 픽셀 수를 얻거나 rem의 카운트를 전달하여 많은 rem에서 픽셀 수를 얻을 수 있습니다. 여기 jsFiddle도있다 : ** 만 W3C standars에 따라 http://jsfiddle.net/drmyersii/mr6eG/

var rem = function (count) 
{ 
    var unit = $('html').css('font-size'); 

    if (typeof count !== 'undefined' && count > 0) 
    { 
     return (parseInt(unit) * count); 
    } 
    else 
    { 
     return parseInt(unit); 
    } 
} 
관련 문제