【问题标题】:$(li).width() returning value which includes padding?$(li).width() 返回值包括填充?
【发布时间】:2013-07-17 16:41:44
【问题描述】:

http://jsfiddle.net/MeoMix/8zg2V/83/

我有以下 jsFiddle。这个想法是,当显示一个太长的上下文菜单项时,它会以省略号呈现,但在鼠标悬停时它会平移文本。

有问题的代码:

//Provides helper methods for non-specific functionality.
define('helpers', [], function () {
    'use strict';

    return {
        scrollElementInsideParent: function(element, parent) {
            //  Scroll the element if its too long to read.
            $(element).mouseover(function () {

                var distanceToMove = $(this).width() - $(parent).width();

                console.log("My width and parent width:", $(this).width(), $(parent).width());

                $(this).animate({
                    marginLeft: "-" + distanceToMove + "px"
                }, {
                    //  Just a feel good value; scales as the text gets longer
                    duration: 15 * distanceToMove,
                    easing: 'linear'
                });

            }).mouseout(function () {
                $(this).stop(true).animate({ marginLeft: 0 });
            });
        }
    };

在这里我记录了被滚动元素的宽度以及它的父元素的宽度。控制台输出:

我的宽度和父宽度:360 230

但这在查看指标时似乎不正确:

这是为什么?

【问题讨论】:

  • 你有box-sizing: border-box吗?
  • 尝试使用outerWidth()
  • @bfavaretto 你可以看到 jsfiddle。他们没有 box-sizing:border-box 。 Terry outerWidth() 返回与 .width() 和 .innerWidth() 和 .outerWidth(true) 相同的值。
  • 你在开玩笑吧? this 引用<a> 元素,其宽度为auto,最终宽度为230px。你为什么看<li>
  • @SeanAnderson 也许我又误会了。让我再看一遍

标签: javascript jquery css width


【解决方案1】:

在您的代码中,parent 参数指的是<ul>。使用$(this).parent() 获取<li>

演示: http://jsfiddle.net/EsL2X/

【讨论】:

  • 谢谢。就在我的鼻子底下。我很感激。 :)
  • @SeanAnderson 完全没问题,下次想想调试那种东西 :) 我很高兴你得到了解决它的答案!
  • 哦,是的.. 我昨晚很晚才做这个,以为我已经探索了所有的选择。显然,我今天早上发现这一点的心态是错误的。干杯。
  • @SeanAnderson 嘿,这就是这个地方的用途 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2014-06-08
  • 1970-01-01
  • 2020-03-19
  • 2014-11-02
  • 2020-11-24
相关资源
最近更新 更多