使用$ .width()调整元素的大小会变大而不是变窄 [英] Resizing an element using $.width() becomes larger instead of narrower

查看:75
本文介绍了使用$ .width()调整元素的大小会变大而不是变窄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$('#btnw').on('click', function() {
  $('#story').width(90 + 'px');
});

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#story {
  width: 100px;
  background: lightgreen;
  padding-right: 45px;
}

.title {
  background: gold;
  margin: 5px 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='story'>
  <div class='title'>
    lorem
  </div>
</div>
<br>
<button id='btnw'>CLICK</button>

首先-title的顶部和底部边距在哪里?

First of all - where are top and bottom margins on title?

为什么单击buttonbox-sizing丢失了?

And why box-sizing is lost after click on button?

结果-story变大而不是变窄10px;

Result - story becomes larger instead of narrower for 10px;

推荐答案

您使用的方法不正确,请改用css()

You are using the method incorrectly, use css() instead

有关更多信息,请参见jQuery > 文档

See the jQuery docs for more info

.css(width).width()之间的区别在于后者 返回无单位像素值(例如400),而前者 传回完整单位的值(例如400px). .width() 当需要在元素中使用元素的宽度时,建议使用此方法 数学计算

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation

$('#btnw').on('click', function() {
  $('#story').css('width', '90px');
});

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#story {
  width: 100px;
  background: lightgreen;
  padding-right: 45px;
}

.title {
  background: gold;
  margin: 5px 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='story'>
  <div class='title'>
    lorem
  </div>
</div>
<br>
<button id='btnw'>CLICK</button>

这篇关于使用$ .width()调整元素的大小会变大而不是变窄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆