Chrome提供了错误的元素宽度

时间:2011-05-26 08:54:03

标签: javascript google-chrome mootools

我在Mootools中制作了一个工具提示类,它取决于获取工具提示元素的宽度以使其在目标上居中。

除了Chrome之外,它在所有浏览器中运行良好,每次重新加载页面时都会为元素宽度提供两个截然不同的数字。当我在CSS中设置宽度100和高度20时,Chrome Web开发人员检查器会正确显示尺寸。但是当我刷新页面时,Chrome会记录出像1904这样的疯狂人物,而我的元素位于远离侧面的位置。

我尝试过使用这些获取宽度的不同方法,或者使用display:none或z-index隐藏工具提示:

  • getDimensions()
  • 的getSize()
  • 的getStyle( '宽度')
  • element.offsetWidth

都有类似的结果。任何善良的人都可以建议解决方法,或者告诉我为什么Chrome会以这种方式表现出来?

谢谢! 佛瑞德

这是我的JS:

Tooltip = new Class({

    Implements: Events,
    Implements: Options,

    options: {
        target: '',                                 // Single element or array of elements
        tip: ''                                     // Element to show          
    },

    initialize: function(options) {
        this.setOptions(options);
        this.setValues();
        this.attachEvents();
    },

    setValues: function() {     
        this.target = this.options.target;
        this.tip = this.options.tip;
        this.tip.setStyle('z-index', -1);                                                   // Hide tip element
        if (this.target == null || this.tip == null) return;                    // We don't have required elements, so return
        this.showing = false;
        this.tipMousedOver = false;
        this.tipDimensions = this.tip.getSize();            // Getting width
        console.log(this.tip);
        console.log(this.tipDimensions.x);
        console.log(this.tip.offsetWidth);

        this.tipFx = new Fx.Morph(this.tip, {
            duration: 350,
            transition: Fx.Transitions.Sine.easeIn,
            link: 'cancel',
            onComplete: function() {
                if (this.showing) this.showing = false;
                else this.showing = true;
            }.bind(this)
        });
    },

    attachEvents: function() {

        this.tip.addEvent('mouseenter', function(e) {
            this.tipMousedOver = true;
            document.removeEvents('click');
        }.bind(this));

        this.tip.addEvent('mouseleave', function(e) {
            document.addEvent('click', this.bodyClick.bind(this));  
        }.bind(this));

        if (typeOf(this.target) == 'element') {
            this.target.addEvent('click', this.toggleTip.bind(this));
        } else {
            this.target.each(function(item, index){
                item.addEvent('click', this.toggleTip.bind(this));
            }.bind(this));
        }

    },

    toggleTip: function(e) {
        e.stopPropagation();
        if (!this.showing) {
            // HIdden, so show
            var posn = e.target.getPosition();
            var vPosn = posn.y;
            var hPosn = posn.x;
            var targetWidth = e.target.getSize().x;
            this.tip.setStyle('z-index', 1);
            this.tip.setStyle('top', vPosn - (this.tipDimensions.y + 10));
            this.tip.setStyle('left', (hPosn + targetWidth /2) - (this.tipDimensions.x / 2));       // Positions middle of tip over middle of target
            console.log('targetWidth: ' + targetWidth + ' tipDimensions.x: ' + this.tipDimensions.x);
            this.tipFx.start({'opacity': [0, 1]});
            document.addEvent('click', this.bodyClick.bind(this));
        } else {
            // Visible, so hide
            if (!this.tipMousedOver) {
                this.tipFx.start({'opacity': 0});
                this.tip.setStyle('z-index', 1);
                document.removeEvent('click', this.bodyClick);
            }       
        }
    },

    bodyClick: function(e) {
        this.tipFx.start({'opacity': 0});
        this.tip.setStyle('z-index', 1);
        document.removeEvents('click', this.bodyClick);
    }

});



window.addEvent('domready', function(){

    new Tooltip({
        target: $('comments-list').getElements('.shareLink'),
        tip: $('shareTip')
    });

});

HTML:

<!DOCTYPE html>
<html>
<head>

    <script src="js/mootools-core-1.3.2-full-compat.js"></script>
    <script src="js/mootools-more-1.3.2.1.js"></script>

<script src="comments_new_click.js"></script>

<link href="comments_new.css" type="text/css" rel="stylesheet">
</head>
<body>

    <ul id="comments-list">
        <!-- START COMMENT ITEM -->
        <li id="CommentKey-f8b1-45f2-b4f6-68ba740ca9c3" class="commentItem">
                <div class="commentTop clrd">
                    <span class="badges">
                        <img style="width: 32px; height: 32px;" src="" alt="" title="">
                        <img style="width: 32px; height: 32px;" src="" alt="" title="">
                    </span>
                    <a class="avatar" href="javascript:;" title="">
                        <img src="" alt="Photo of editor1">
                    </a>                
                    <a class="username" href="javascript:;" title="">And Finally</a>
                </div>
                <div class="commentBody clrd">

                    <div class="commentOver">
                        <div class="submDateAndTime">26 April 2011</div>
                    </div>                  

                    <div class="commentSide">
                        <div class="likeDislike">
                            <a class="pluck-like alreadyvoted" href="javascript:;" title="">Like</a>
                            <span class="pluck-score">00000</span>
                            <a class="pluck-dislike" href="javascript:;" title="">Dislike</a> 
                        </div>
                    </div>                  

                    <div class="commentText">
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur a sapien vitae enim sagittis sodales at sit amet leo. Aenean cursus euismod blandit. Suspendisse potenti. Pellentesque vestibulum nisi id dui aliquet consequat. Nulla egestas tortor vel metus dapibus luctus. Nullam rhoncus ullamcorper lorem, non vehicula nulla euismod viverra. Morbi tempus dui ut ipsum interdum ut dapibus est venenatis. 
                    </div>

                </div>
                <div class="commentBottom clrd">

                    <div class="getReplies">
                        <a href="javascript:;" title="Show replies to this comment">See Replies</a>
                        <span>2</span>
                    </div>

                    <!-- To delete -->
                    <div style="display:block;clear:both;float:none;height:0"></div>

                </div>

                <!-- REPLIES -->
                <div id="nestedcommentslist-CommentKey:f8b1-45f2-b4f6-68ba740ca9c3" class="repliesWrapper"></div>
                <!-- END REPLIES -->

        </li>
        <!-- END COMMENT ITEM -->
                <!-- START COMMENT ITEM -->
        <li id="CommentKey-f8b1-45f2-b4f6-68ba740ca9c3" class="commentItem">
                <div class="commentTop clrd">
                    <span class="badges">
                        <img style="width: 32px; height: 32px;" src="http://z.x.co.uk/ver1.0/Content/images/store/5/6/3262-4af5-8654-ef59a25b24e1.Full.png" alt="" title="">
                        <img style="width: 32px; height: 32px;" src="http://z.x.co.uk/ver1.0/Content/images/store/5/6/3262-4af5-8654-ef59a25b24e1.Full.png" alt="" title="">
                    </span>
                    <a class="avatar" href="javascript:;" title="">
                        <img src="http://z.x.co.uk/ver1.0/Content/images/store/13/3/f175-45b8-931b-28619aadfd2a.Small.png" alt="Photo of editor1">
                    </a>                
                    <a class="username" href="javascript:;" title="">And Finally</a>
                </div>
                <div class="commentBody clrd">

                    <div class="commentOver">
                        <div class="submDateAndTime">26 April 2011</div>
                    </div>                      

                    <div class="commentText">
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur a sapien vitae enim sagittis sodales at sit amet leo. Aenean cursus euismod blandit. Suspendisse potenti. Pellentesque vestibulum nisi id dui aliquet consequat. 
                    </div>

                </div>
                <div class="commentBottom clrd">

                        <div class="getReplies">
                            <a href="javascript:;" title="Show replies to this comment">See Replies</a>
                            <span>2</span>
                        </div>

                        <div class="share">
                            <a href="javascript:;" class="abuse" title="">Report abuse</a>
                            <a href="javascript:;" class="shareLink" title="">Share</a>
                        </div>

                        <!-- To delete -->
                        <div style="display:block;clear:both;float:none;height:0"></div>

                </div>
                <!-- REPLIES -->
                <div id="nestedcommentslist-CommentKey:f8b1-45f2-b4f6-68ba740ca9c3" class="repliesWrapper"></div>
                <!-- END REPLIES -->

        </li>
        <!-- END COMMENT ITEM -->
    </ul>

    <div id="shareTip" class="popup">Share and things</div>
</body>
</html>

CSS:

body {
  font-family: Arial,Helvetica,sans-serif;
  font-size: 62.5%;
}

#comments-list {
    width: 480px;
    margin: 20px auto;
    border: 1px solid #ccc;
    list-style-type: none;
    padding: 0;
}

.commentItem {
    margin-left: 0;
    padding-left: 0;
    font-size: 13px;
}

.avatar {
    margin-right: 5px;
}

.avatar img {
    width: 45px;
    height: 45px;
}

.commentTop {
    position: relative;
    padding: 5px;
    min-height: 48px;
    background: #e8e8eb;
}

.username {
    position: absolute;
    top: 5px;
    height: 1em;
    font-size: 14px;
    text-decoration: none;
}

.badges {
    float: right;
}

.badges img {
    margin-left: 2px;
}

.commentBody {
    padding: 5px;
    background: #f3f2f2;
}

.commentText {
    margin-right: 75px;
    line-height: 16px;
}

.commentOver {
    clear: both;
    float: none;
    height: 14px;
    padding: 0 3px 10px 0;
}

.submDateAndTime {
    float: left;
    color: #777;
    font-size: 11px;
}

.getReplies {
    float: left;
    padding: 0;
}

.getReplies a {
    background-color: #ED9430; /* Put elsewhere */
  background-image: url("http://z.x.co.uk/images/comments-wide.png");
  background-position: -508px -245px;
  background-repeat: no-repeat;
  display: block;
  float: left;
  height: 20px;
  text-indent: -9999px;
  width: 60px;
}

.getReplies span {
  background-image: url("http://z.x.co.uk/images/comments-wide.png");
  background-position: -569px -245px;
  background-repeat: no-repeat;
  display: block;
  float: left;
  font-size: 14px;
  font-weight: bold;
  height: 21px;
  padding-left: 2px;
  text-align: center;
  width: 41px;
  line-height: 19px;
}

.commentBottom {
    padding: 5px;
    background: #f3f2f2;
}

.share {
    float: right;
}

.popup {
    position: absolute;
    border: 1px solid #ccc;
    padding: 10px;
    background: #fff;
    z-index: 1;
}

.hidden {
    display: none;
}

#shareTip {
    width: 100px;
    height: 20px;
    overflow: hidden;
}

=======================================

LATER

对于遇到类似问题的其他人,我发现当我在显示它之前测量尖端元素时它会消失,而不是在对象初始化时。所以我把我的揭示方法改为:

toggleTip: function(e) {
    e.stopPropagation();
    if (!this.showing) {
        // HIdden, so show
        var posn = e.target.getPosition();
        var targetPosnY = posn.y;
        var targetPosnX = posn.x;
        var targetWidth = e.target.getSize().x;
        var targetHeight = e.target.getSize().y;
        var tipSize = this.tip.getSize();
        var tipPosnY = targetPosnY - (tipSize.y + 10);
        var tipPosnX = targetPosnX - (targetWidth / 2);
        this.tip.setStyle('z-index', 1);
        this.tip.setPosition({x: tipPosnX, y: tipPosnY});
        this.tipFx.start({'opacity': 1});
        document.addEvent('click', this.bodyClick.bind(this));
    } else {
        // Visible, so hide
        if (!this.tipMousedOver) {
            this.tipFx.start({'opacity': 0});
            this.tip.setStyle('z-index', 1);
            document.removeEvent('click', this.bodyClick);
        }       
    }
},

我还发现setPosition()是一种比setStyle()更可靠的元素定位方式。

1 个答案:

答案 0 :(得分:2)

如果您只定位最近的浏览器,则可以使用window.getComputedStyle返回屏幕上绘制的所有css属性和值。

或者只是使用它来制作chrome的解决方法。