一旦用户选择了一些文本,我就尝试显示工具提示。客户选择文本后,我将弹出窗口放置在所选文本附近,因为我使用此功能,但我得到了错误的 x
和 y
位置。有什么帮助吗?
$(document).ready(function(){
$('.document').click(function(e) {
if(getSelectedText() !="") { //checking user selected some text?
var x = e.pageX;
var y = e.pageY;
$(".savetooltipAll").css("top",y); //wrong not near to text selection
$(".savetooltipAll").css("left",x); //wong not near to text selection
$(".savetooltipAll").show();
} else {
$(".savetooltipAll").hide();
}
})
});
最佳答案
很快就制作了一个版本。 需要更改/优化定位以适应您的 HTML 代码和需求。
Jsfiddle: http://jsfiddle.net/j5jzaa5e/
$(document).ready(function(){
$('body').mouseup(function(e) {
// Get the selection range
var range = window.getSelection().getRangeAt(0);
// Check if text was actually selected
if (!range.collapsed) {
// Get bounds & set tooltip pos
var bounds = range.getBoundingClientRect();
var x = bounds.left + ((bounds.right - bounds.left - $(".savetooltipAll").outerWidth()) / 2);
var y = bounds.top - $(".savetooltipAll").outerHeight() + $(window).scrollTop();
$(".savetooltipAll").css("top", y + 'px');
$(".savetooltipAll").css("left",x + 'px');
$(".savetooltipAll").show();
} else {
$(".savetooltipAll").hide();
}
})
});
关于javascript - 记录选定的文本位置给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618422/