简体   繁体   中英

Trouble setting css right property

I have made a simple tooltip generator using JQuery 1.10.2 that reads the element's title value.

It's working okay, apart from if the element is to the right of the screen, sometimes the tooltip floats off the edge of the page.

If the element is near the right of the page, I'd like to positioning it somewhere close to the right-edge of the element.

My code is below, and also a JSFiddle. All input appreciated!

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/

If you hover on the left element it sets the CSS left but when you hover on the right element you only set the CSS right property, so the final style will have both left and right set.

You need to reset the left back to its default value first (and probably the same for the other properties), for example see demo where I have added the following code:

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

You were so close.

FIDDLE

You just need to reset the left and right styles when you're not using them:

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

Just calculate the left instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM