[英]JQuery width() returning wrong value?
我处于这样的情况:
我们有两个类似的弹出窗口,这些弹出窗口是由工厂(使用Javascript)生成的,因此它们共享相同的公共事件和功能。 其中之一是名为resizeFormRowService
自定义大小调整功能。 当浏览器窗口触发resize
事件时,它将被调用。
由于弹出窗口的结构类似于重复
<div class="row">
<div> //label </div>
<div> //data </div>
</div>
resizeFormRowService
首先使用类row
获取父div的宽度,然后将其第一个div子级(即标签)设置为固定宽度(如140px),然后将第二个div的宽度设置为“父级-第一个子级”。 全部由JQuery完成(如下所示)
我发现Chrome中的一个弹出窗口有一个奇怪的行为(我正在比较两个如上所述的类似弹出窗口)。
计算出的第二个子div的宽度(即数据)比其他弹出窗口的相应字段大5px。 因此,我在resizeFormRowService
记录了一些resizeFormRowService
以跟踪发生了什么。
StandardTemplatePopup.prototype.resizeFormRowService = function () { var self = this; var $popUp = self.getPopup(); ... var $rows = $popUp.find('.row'); $rows.each(function () { var $this = $(this); var $firstDiv = $this.find('div:first'); var $secondDiv = $this.find('div:eq(1)'); var labelColWidth = self.options('labelColWidth'); // labelColWidth is something we can config, so both popup firstDiv's width is the same // so I think the problem must be in $this.width() $firstDiv.width(labelColWidth); //Add by me, want to see which row is this console.log($this); //Add by me, see this row's width console.log($this.width()); var width = $this.width() - $firstDiv.outerWidth() - 0.5; $secondDiv.width(width); }); ... };
在两个弹出窗口上运行此命令,一个记录270px
,另一个记录265px
! 因此,我尝试查看它们是哪几行,在这一点上,我认为也许第一个弹出窗口中有一些脚本会更改行的边距/填充,从而更改其宽度,但令人惊讶的是,情况并非如此
这是第一个弹出窗口
这是第二个弹出窗口
如图所示,第二个子div的计算宽度相差5px,但是父级的行宽度完全相同 ,这与我在resizeFormRowService
记录的内容相矛盾!
所以我的问题是:是否存在导致我的问题的JQuery width()的任何已知问题? 如果否,那么任何指向潜在原因的建议都会受到欢迎。
编辑:
我希望这可以通过反复试验来提示我的队友之一,在第一个弹出窗口的末尾添加一个空的div
<div class="col-xs-12"> </div>
然后一切正常...两个弹出窗口都将正确调整大小。
PS1:较小的结果:265像素是正确的预期结果
PS2:图像中的高度差是由于第二个子div的宽度计算错误而导致的内容太宽而无法在一行中显示,因此高度会自动增加
我只想回答这个问题,因为评论不是很有见地。
对我来说,您的计算似乎太快了,无法保持任何预设值。 像这样说,CSS过渡肯定会100%为您搞砸。 我个人会更像这样编码(我自己是一名前端作者)
$rows.each(function () {
var $this= $(this);
var $firstDiv = $('div:first', $this);
var $secondDiv = $('div:eq(1)', $this);
var labelColWidth = self.options('labelColWidth');
// labelColWidth is something we can config, so both popup firstDiv's width is the same
// so I think the problem must be in $this.width()
$firstDiv.width(labelColWidth);
//Add by me, want to see which row is this
console.log($this);
//Add by me, see this row's width
console.log($this.width());
//why recalculate the $firstDiv.width when you have labelColWidth?
//try to avoid simple names like "width" for prevention of double naming
var newWidth = $this.width() - labelColWidth - 0.5;
$secondDiv.width(newWidth);
});
-我应该提到,当您插入诸如: after
或: before
时,诸如div:first
和div:eq(1)
类的选择器往往会中断。 我建议您改用类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.