[英]Trouble setting css right property
I have made a simple tooltip generator using JQuery 1.10.2 that reads the element's title
value. 我使用JQuery 1.10.2制作了一个简单的工具提示生成器,该生成器读取元素的title
值。
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. 我的代码在下面,还有一个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
}
});
}
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. 如果将鼠标悬停在left元素上,它将CSS设置为left
但是当您将鼠标悬停在right元素上时,仅设置CSS right
属性,因此最终样式将同时设置left
和right
。
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: 您需要首先将left
重设为其默认值(其他属性可能也是如此),例如, 请参见演示 ,在其中我添加了以下代码:
if (ttRightSide < $(window).width()) {
tt.css({
top: (y + 15),
right: 'auto',
left: (x + 5)
});
} 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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.