使用width()方法并以百分比形式返回值

Using the width() method and returning the value as a percentage

本文关键字:百分比 返回值 width 方法 使用      更新时间:2023-09-26

所以我想使用width()方法来返回我网站上元素的宽度,默认情况下它将以像素为单位显示。

我正在阅读W3Schools,您可以将值更改为许多不同的单位,如px, em, pt等。

我想返回宽度作为一个百分比,我怎么能做到这一点?

下面是我的代码: Jquery

$('.range-control').each(function(){
    var container = $(this),
        input = container.find('input'),
        output = container.find('output'),
        rangeWidth = input.width(),
        thumbWidth = container.attr('data-thumbwidth'),
        startValue = input.val(),
        startOffset = ((rangeWidth - thumbWidth) / 100) * startValue;
    output
        .css({
            'left' : startOffset
        });
    $(input).on('input', function(){
        var value = this.value,
            offset = ((rangeWidth - thumbWidth) / 100) * value;
        output
            .val(value)
            .css({
                'left' : offset
            });
    });
});

任何帮助将非常感激!!

不能用直接计算吗?

var parentWidth = $(this).parent().width();
var thisWidth = $(this).width(); 
var percentWidth = (thisWidth/parentWidth)*100+"%";