【问题标题】:Use jquery to increase width of container by 10 rem使用 jquery 将容器的宽度增加 10 rem
【发布时间】:2013-04-11 22:12:08
【问题描述】:

如何使用 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());

我的问题是代码中的cmets。

【问题讨论】:

  • 同意你的问题,但我认为rem 单位仅适用于 Fonts 根据 W3C 标准参见:w3.org/TR/css3-values
  • 是的,但是这些天 em/rem 单位在应用程序中被广泛使用,因为这允许页面内容根据设备大小进行调整。随着字体大小的变化,其他所有内容都会相应地变化。

标签: jquery css height width


【解决方案1】:

我想,取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/

【讨论】:

  • 做得很好@xpy。我认为应该存在一些优雅/简单的解决方案。你的也不错:)
【解决方案2】:

决定使用 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多