JQuery-更改按钮';在不更改字体大小的情况下更改字体大小

JQuery-更改按钮';在不更改字体大小的情况下更改字体大小,jquery,css,Jquery,Css,当我改变按钮的字体大小时,大小也会改变。我的问题是我不能给按钮一个预定义的大小,所以我尝试用.css('width','-=4px')来修复它 但这是行不通的。希望有人能帮助我 HTML <input id="b1" type="button" value="Hello world" /> <input id="b2" type="button" value="Blubba blib" /> <input id="b3" type="button" value="B

当我改变按钮的字体大小时,大小也会改变。我的问题是我不能给按钮一个预定义的大小,所以我尝试用
.css('width','-=4px')来修复它

但这是行不通的。希望有人能帮助我

HTML

<input id="b1" type="button" value="Hello world" />
<input id="b2" type="button" value="Blubba blib" />
<input id="b3" type="button" value="Bl" />
<input id="b4" type="button" value="Blubba 55" />
Exmaple

提前谢谢

Peter

您应该尝试从一开始就为按钮设置一个更大的大小,这样当文本变为粗体时,大小不会改变。

编辑:

在加粗之前,只需增加一些额外的宽度

$('input:button').width(function(){
    return $(this).outerWidth() + 20;
}).click(function() {
    $(this).css('font-weight', 'bold').siblings().css('font-weight', 'normal');
});

好了。

我有你的问题

你可以找出按钮的宽度,然后像下面那样减小按钮的宽度

            $('*').css('font-weight', 'normal');
            $(this).css('font-weight', 'bold');
            var wdth = $(this).width();
            wdth = wdth - 4;
            $(this).css({ width: wdth+'px' });
所以当你点击这个按钮时,它会找出按钮的宽度,然后 减小宽度

最终,您可以检查字体宽度属性,并根据您的要求使其交替减小或增大


此外,您还可以设置要实现的大小百分比。

在使用此代码执行任何操作之前,您必须给按钮一些填充,以便当按钮内的文本展开时,它们不会溢出。此代码使用
.outerWidth
获得正确的宽度并相应调整按钮

$('input:button').click(function() {
    var w = $(this).outerWidth();

    $(this).css({
        'font-weight': 'bold',
        'width': w
    }).siblings().css({
        'width': 'auto',
        'font-weight': 'normal'
    });
});

请参阅:

嗨,Stefanvds,您的解决方案不起作用:(>我知道您在那里做了什么-但不,让它们保持大小的不是额外的宽度-而是您为它们指定了一个固定的宽度。如果您删除
+20px
,它也会起作用。这基本上是我的解决方案,但更好(虽然不太灵活,但如果你想动态更改按钮的内容),所以这里是+1。我也在将你的解决方案更新为更高效的解决方案,希望你不会介意。你能给我一个JSFIDLE exmaple吗?
$('input:button').click(function() {
    var w = $(this).outerWidth();

    $(this).css({
        'font-weight': 'bold',
        'width': w
    }).siblings().css({
        'width': 'auto',
        'font-weight': 'normal'
    });
});