我有一个div,我希望在悬停span元素时相对于鼠标定位。 此代码在这里,它似乎不起作用。 div只显示。
var x;
var y;
$(document).mousemove(function(event) {
x = event.pageX;
y = event.pageY;
});
$('#sp').hover(function() {
document.getElementById('sp_info').style.display='';
document.getElementById('sp_info').style.position='absolute';
document.getElementById('sp_info').style.left=x;
document.getElementById('sp_info').style.top=y;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="sp_info" style="display:none">
<p>Text that should move with mouse position</p>
</div>
<div class="panel-body">
<table class="table table-bordered">
<tr>
<td class="active"><center><span id="sp">Here is a test hovering test</span></center>
</td>
</tr>
</table>
</div>
如果您有任何想法,请告诉我。
答案 0 :(得分:2)
在代码中查看内联注释:
// On mousemove on #sp element
$('#sp').mousemove(function(e) {
// Get the current mouse positions
var x = e.pageX,
y = e.pageY;
// Update the position of `#sp_info` dynamically
$('#sp_info').css({
'position': 'absolute',
'top': y + 5, // Leave some margin
'left': x + 5, // Leave some margin
'display': 'block'
});
}).mouseleave(function() {
$('#sp_info').hide();
});
答案 1 :(得分:0)
var x;
var y;
$(document).mousemove(function(event) {
x = event.pageX;
y = event.pageY;
$('#sp').hover(function() {
$("#sp_info").css({position:"absolute", left:x, top:y});
});
});
使用jQuery&#39; s css function
。阅读更多相关信息here。
答案 2 :(得分:0)
var x;
var y;
$(document).mousemove(function(event) {
x = event.pageX;
y = event.pageY;
document.getElementById('sp_info').style.display='';
document.getElementById('sp_info').style.position='absolute';
document.getElementById('sp_info').style.left=x+'px';
document.getElementById('sp_info').style.top=y+'px';
});
$('#sp').hover(function() {
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="sp_info" style="display:none">
<p>Text that should move with mouse position</p>
</div>
<div class="panel-body">
<table class="table table-bordered">
<tr>
<td class="active"><center><span id="sp">Here is a test hovering test</span></center>
</td>
</tr>
</table>
</div>
&#13;
答案 3 :(得分:0)
您应该在悬停事件中设置left
和top
$('#sp').hover(function(event) {
$('#sp_info').show().css({
position: 'absolute',
left: event.pageX,
top: event.pageY,
});
}, function() {
$('#sp_info').hide();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="sp_info" style="display:none">
<p>Text that should move with mouse position</p>
</div>
<div class="panel-body">
<table class="table table-bordered">
<tr>
<td class="active">
<center><span id="sp">Here is a test hovering test</span>
</center>
</td>
</tr>
</table>
</div>
&#13;