使用javascript或jquery按下按钮时,在文本区域插入图像

Insert image in textarea when button is pressed using javascript or jquery?

本文关键字:文本 区域 图像 插入 按钮 javascript jquery 使用      更新时间:2023-09-26

我在html中设计了一个文本区域和按钮。我想在按下按钮时在文本区域插入图像。在javascript或jquery中它是如何实现的?

文本区域只能包含文本。

文本区域只能包含文本,但可以重叠元素。以下是一个示例:http://jsfiddle.net/2qMb3/1/

这使用了一个样式化的div而不是图像,但您可以很容易地使用图像而不是div。

您可能需要研究使用所见即所得编辑器,如TinyMCE或CKEditor。

正如其他人所说,TextArea只包含Text,但你可以尝试这样的东西:

<textarea id="x" rows="5" cols="20">hellooo</textarea>
$('#buttonId').click(function(){
    $('#x').css('background',urlOfImage)
});

以下是一个工作示例;你必须根据自己的要求来操作它。

您可以使用jQuery在点击时向文本区域添加简单的CSS

HTML

<textarea id="message" rows="2" cols="20"></textarea>
<input type="button" value="Add image to textarea" id="add_image" />

CSS:

<style>
#message{
  padding-left : 30px; // This will prevent the text from overlapping the image
}
#add_image{
 display: block; //just making the button appear in its own line
}
</style>

Javascript:

<script>
$(document).ready(function() {
    $('#add_image').click(function() {
      $('#message').css({
          'background' : 'url(http://lorempixel.com/20/40) no-repeat',
      });
    });
});
</script>

在行动中看到它:http://jsfiddle.net/gksTQ/