麻烦设置css正确的属性

时间:2013-07-16 15:11:25

标签: javascript jquery css

我使用JQuery 1.10.2制作了一个简单的工具提示生成器,它读取了元素的title值。

它工作正常,除了元素位于屏幕右侧之外,有时工具提示会浮动到页面边缘。

如果元素靠近页面右侧,我想将它放在靠近元素右边缘的位置。

我的代码在下面,也是一个JSFiddle。所有的意见都赞赏!

function BuildTipsV3() {
    var tt = $("#ttfloat");
    $("[title]").on({
        mouseenter: function() {
            // set tooltip
            var o = $(this).offset();
            var y = o.top;
            var x = o.left;
            var tooltip = $(this).attr('title') || $(this).data('title');
            $(this).attr('title', '');
            $(this).data('title', tooltip);
            tooltip = tooltip.replace(/(\r\n|\n|\r)/gm, "<br/>");
            tt.html(tooltip);
            // position tooltip and show
            var ttRightSide = x + tt.width();
            if (ttRightSide < $(window).width()) { 
                tt.css({ top: (y + 15), left: (x + 5) });
            } else { 
                tt.css({ top: y, right: 0 }); // <-- problem (right:0) doesn't work
            }
            tt.show();
        },
        mouseleave: function () {
            $("#ttfloat").hide();
            $(this).attr('title', $(this).data('title')); // reset for accessibility
        }
    });
}

http://jsfiddle.net/HSfHD/2/

3 个答案:

答案 0 :(得分:1)

如果您将鼠标悬停在 left 元素上,则会设置CSS left,但当您将鼠标悬停在右侧元素上时,您只需设置CSS {{1} } property,因此最终样式将同时设置rightleft

您需要先将right重置为默认值(其他属性可能相同),例如see demo,其中添加了以下代码:

left

答案 1 :(得分:1)

你太近了。

FIDDLE

您只需在不使用时重置leftright样式:

if (ttRightSide < $(window).width()) {
    tt.css({
        top: (y + 15),
        left: (x + 5),
        right:'auto'
    });
} else {
    tt.css({
        top: y + 15,
        right: 0,
        left:'auto'
    });
}

答案 2 :(得分:0)

只需计算左边。

tt.css({
    top: y+20,
    left: $(window).width() - tt.width() - 20
});