我想在我点击鼠标的任何地方放置一个动态创建的 Html Span 元素。 我想使用从点击获得的坐标,但它没有用。
HTML:
<div id = "test" style="background:#7FFFD4; width:1000px; margin:20px; height:20px; position: relative;">
Area For Test
</div>
脚本
$(document).ready(function () {
$("#test").click(function (e) {
$('#test').append('<span id = "abc">' + 'sampleText' + '</span>');
var x = Math.round(e.pageX - posX) + "px";
var y = Math.round(e.pageY - posY)+ "px";
$('#abc').css({ 'position': 'absolute', 'top': x, 'left': y});
});
});
那么有没有一种很好的方法可以将 Span 元素定位在我点击的位置。
最佳答案
我稍微修改了您的代码段。 请在这里找到它(https://jsfiddle.net/sdilipsam/7x47ejce/)。
您可以在 What is the difference between screenX/Y, clientX/Y and pageX/Y? 中阅读有关 clientX/Y 与 Page X/Y 的更多信息
<div id="test">Area For Test</div>
$(document).ready(function () {
$("#test").click(function (e) {
$('.float-span').remove();
$('body').append('<span id = "abc" class="float-span">' + 'sampleText' + '</span>');
var x = Math.round(e.clientX) + "px";
var y = Math.round(e.clientY) + "px";
$('.float-span').css({
'top': y,
'left': x
});
});
});
#test {
background:#7FFFD4;
width:500px;
height:500px;
margin:20px;
position: relative;
}
.float-span {
position:absolute;
}
关于javascript - 将 "Span"Html 元素定位到我单击鼠标的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32846282/