使用jquery将容器的宽度增加10 rem

sac*_*024 9 css jquery height width

如何使用jquery增加10rem的元素宽度.问题是Jquery总是以像素为单位返回宽度/高度,我们想要更新其他单位的高度/宽度.

示例: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());
Run Code Online (Sandbox Code Playgroud)

我的问题是代码中的注释.

xpy*_*xpy 13

我想,使用font-sizehtml元素将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());
    }
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/4NkSu/1/


Dav*_*ers 6

决定使用jquery发布更新的答案.您可以在没有参数的情况下调用函数来获取一个rem中的像素数,或者您可以传入rem的计数来获取该许多rem中的像素数.这里也是一个jsFiddle: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);
    }
}
Run Code Online (Sandbox Code Playgroud)