如何在靠近元素的适当位置显示提示?
问题描述:
我在网页上有以下DIV:如何在靠近元素的适当位置显示提示?
<div id="tip">
Tip text here...
</div>
而下面的一个:
<div class="element">
Element text here...
</div>
而且下面的JS代码:
$(document).ready(function() {
$('.element').hover(function() {
$('#tip').css('top', $('.element').position().top);
$('#tip').css('left', $('.element').position().left);
$('#tip').fadeIn();
}, function() {
$('#tip').fadeOut();
});
});
它显示在左上角尖的页面。我如何修复此代码以显示与元素位置相同的提示? (我不能将小费和元素放在代码附近)
非常感谢您的帮助!
答
.POSITION是相对父,尝试.offset,谁是相对于文档
答
给Div标签标题显示工具提示..。尝试像下面....
<div title="ToolTip for Hello World">
Hello World
</div>
看到这个小提琴:http://jsfiddle.net/TPyKS/5/
+0
我需要定制div作为提示 - 而不是标准的工具提示。 – Dmitry 2013-02-10 17:32:06
答
试试这个:
HTML
<div class="element">
Element text here...
</div>
<div id="tip">
Tip text here...
</div>
CSS
#tip{
position: absolute;
display: none;
background: #ccc;
padding: 10px;
}
.element:hover + #tip{
display: block;
}
div{
float: left;
}
答
这就是我会做一个提示:
的Html
<div class="tip" title="Title here">
Element text here...
</div>
jQuery的
$(document).ready(function() {
$('.tip').each(function(i, e) {
var $this = $(e),
originalTitle = $this.attr('title'),
//Keep the title
$title = $('<p class="tooltip" />').html(originalTitle);
//Remove initial one
$this.attr('title', '');
$title.appendTo($this);
});
$('.tip').hover(function() {
$(this).find('.tooltip').fadeIn();
}, function() {
$(this).find('.tooltip').fadeOut();
});
});
的CSS
.tip {
position:relative;
}
.tooltip {
position:absolute;
display:none;
}
只需用CSS设置工具提示的位置就可以了。 title属性允许禁用JavaScript的用户也可以看到它们。
参见fiddle。
答
您可以尝试使用下面的函数来帮助您确定一个DOMElement的绝对坐标。可以提供左侧和顶部参数以获得从元素的左上角相对偏移的位置。
var findAbsolutePosition = function(domElement, left, top) {
if (!parseInt(left)) {
left = 0;
} else {
left = parseInt(left);
}
if (!parseInt(top)) {
top = 0;
} else {
top = parseInt(top);
}
var box = domElement.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft ||0;
var position = {};
position.y = box.top + scrollTop - clientTop + top*Settings.get('scale');
position.x = box.left + scrollLeft - clientLeft + left*Settings.get('scale');
position.width=box.width;
position.height=box.height;
return position;
}
其他方法是动态地将尖端元素插入需要提示的元素附近的DOM。使用哪种方法取决于你
另外我也使用'位置:绝对;'在css上提示。 – Dmitry 2013-02-10 18:21:30