如何使用坐标在图像上书写文字?

时间:2016-06-06 04:40:55

标签: javascript jquery css

我有一个图像,当我点击图像中的1点时,我希望在图像上显示一些文字,我的问题是文字不显示在鼠标点,它显示在鼠标下方。 这是我的代码: 脚本:

<script type="text/javascript">
    $(function() {
        $("#imgEx").click(function(e) {
            var offset = $(this).offset();
            var relativeX = (e.pageX - offset.left);
            var relativeY = (e.pageY - offset.top);
            //alert("X: " + relativeX + ' -' + " Y: " + relativeY);
            var text = document.getElementById('textEx');
            text.textContent = "X: " + relativeX + ' -' + " Y: " + relativeY;
            text.style.left = relativeX + "px";
            text.style.top = relativeY - 30 + "px"; // minus one range you want display text in image ( my number is 30 to display in mouse point)
        });

    });

</script>

和我的表格:

<form method="POST">
    <div class="image">
        <img id="imgEx" type="image" alt="image" src="./src/assets/cat.jpg" style="width:700px; height:600px" >
        <h2 id="textEx"></h2>
    </div>
</form>

2 个答案:

答案 0 :(得分:1)

wrapper设为relative,将content设为absolute

同时使用span元素代替h元素h元素本身与浏览器特定style(css)

相关联

&#13;
&#13;
$(function() {
  $("#imgEx").click(function(e) {
    var offset = $(this).offset();
    var relativeX = (e.pageX - offset.left);
    var relativeY = (e.pageY - offset.top);
    var text = document.getElementById('textEx');
    text.textContent = "X: " + relativeX + ' -' + " Y: " + relativeY;
    text.style.left = relativeX + "px";
    text.style.top = relativeY + "px";
  });
});
&#13;
.image {
  position: relative;
}
#textEx {
  position: absolute;
  font-size: 20px;
  font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="POST">
  <div class="image">
    <img id="imgEx" type="image" alt="image" src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" style="width:700px; height:600px">
    <span id="textEx"></span>
  </div>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您只需为#textEx

指定位置:绝对
#textEx{
  position:absolute;
}