gpt4 book ai didi

jquery - $(element).outerWidth(true) 根据主题报告不同?

转载 作者:行者123 更新时间:2023-12-01 01:57:09 25 4
gpt4 key购买 nike

我有一个 jQuery 脚本,它通过普通的 CSS 宽度属性将元素的宽度设置为 50%。

如果我然后输出 outerWidth(true)要获得准确的像素值,它有时与 $(window).width()/2 不对应- 这是基于网站的主题。不幸的是,我无法将这种行为的演示带到网上。

是否有任何特定的 CSS 属性可能导致这种差异?

问题是 outerWidth()例如,正在报告 564px ,但是当我 checkin Safari 检查器时,它显示 580 .所以那个函数的返回是不正确的,我想知道是什么原因。

演示:

http://users.telenet.be/prullen/this/

http://users.telenet.be/prullen/that/

内容(单击红色选项卡时的灰色区域)应该在加载时通​​过负边距隐藏,但由于 jquery 的(不正确?)返回,它不在这些主题之一中(略微显示)。

console.log 调用是:

        console.log('window width / 2 = ' + $(window).width()/2);
console.log('doc width /2 = ' + $(document).width()/2);

console.log('width = ' + defaults.boxWidth);
console.log('width = ' + $slider.css('width'));
console.log('width = ' + $slider.width());
console.log('width = ' + $slider.outerWidth());
console.log('width = ' + $slider.outerWidth(true));

最佳答案

.outerWidth([includeMargin]) - 返回元素的宽度,以及左右填充、边框和(可选)边距(以像素为单位)。

设置[includeMargin] true 的选项将边距添加到此数字:

.outerWidth(true) - 返回元素的宽度,以及左右填充、边框、和边距 , 以像素为单位。

.width() - 返回一个无单位的像素值 不包括 左右填充、边框或边距。

根据 jQuery 文档,仅限 .width() 之间的区别和 .css(width)是后者包括width()的单位('px')只需返回数字(不带“px”)。

因此,如果根据定义,width()不包括边距、填充和边框,那么 css(width) 也不包括

I have a jQuery script, this sets an element's width to 50% via the normal CSS width attribute.



这是将元素本身(不包括边距、填充或边框)设置为其容器的 50%。如果窗口是容器,那么元素的宽度将是它的 50%。

示例:对于 1160 像素宽的窗口,您的脚本将创建一个 1160 的 50% 或 580 像素宽的元素(不包括边距、填充或边框)。

If I then output the outerWidth(true) of that element to get the exact pixel value, it sometimes does not correspond to $(window).width()/2.



当您使用 outerWidth(true) 查看相同的元素时,现在您正在为数字添加边距、填充或边框。

使用我的相同示例:窗口为 1160 像素, $(window).width()/2将是 580。假设您的元素也是 580 像素, .outerWidth(true)将添加(或减去)边距,添加边框并为元素本身添加填充,因此除非边距,填充和边框都为零,否则您不会得到 580。

所以很自然,使用不同的“主题”(使用您的定义),元素可能会有不同的填充、边框和边距。我不能肯定地说,因为我看不到您的任何代码。

只需使用 .width()代替 .outerWidth(true)保持所有主题的一致性。

编辑:

在 Safari 控制台中,我看到 body 上的边距造成你所描述的。在您的 consolidated-screen-2.css 内工作表您有 20 像素的左边距。

在进行计算时,您必须考虑此主体边距。

由于您的 JavaScript 不会动态更新并且这不在 jsFiddle 中,因此我无法进一步测试它。当我在 DOM 中将边距设置为 0 时,我无法在不重新加载页面的情况下调用 JS 重新计算数字,这当然会消除我的 DOM 覆盖。

一种解决方案是坚持使用 .width()。 (忽略边距)在您的所有计算中。

另一种解决方案似乎包括设置 body margin 为零。

编辑 2:

你一直说它报告不正确,但我的屏幕上覆盖了一个半透明的像素标尺实用程序,用于以下内容,一切都在检查...

This page在 1228 像素宽的窗口中。 Ruler 验证了这一点。
console.log('width = ' + $slider.outerWidth(true)); = 1188

1188 40 像素( body 左右边距)= 1228(与标尺相同)

抽屉打开,尺子验证它是 正好 614 像素宽 (没有右边框)。
console.log('width = ' + $slider.css('width')); = 594 像素;

594 20 像素( body 左边距)= 614(与标尺相同)
console.log('width = ' + $slider.width()); = 594

594 20 像素( body 左边距)= 614(与标尺相同)

关于jquery - $(element).outerWidth(true) 根据主题报告不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7983278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com