gpt4 book ai didi

javascript - 在 img 上动态添加文本

转载 作者:行者123 更新时间:2023-11-30 10:36:01 24 4
gpt4 key购买 nike

我还在搜索一些帖子,但我还没有想法。

目标:我有一张图片(黄色便利贴 280px x 280px),现在,我希望能够在用户按下按钮后在便利贴上放置文本,例如“文本”。我对 html 很坚定,但对 javascript 不是很了解。非常感谢!马丁

最佳答案

我就是这样做的。

使用带有便利贴图像的 div 作为背景,并使用子 div 作为注释。

<div class='post-it'>
<div class="note">
</div>
</div>​

div.note 可以轻松定位,因此不会与图像重叠。

.post-it {
background-image: url('http://alternatewrites.com/wp-content/uploads/2012/06/post-it-note-with-a-pin.jpg');
background-repeat: no-repeat;
width: 321px;
height: 321px;
position: relative;
}
.note {
position: absolute;
top: 90px;
right: 30px;
bottom: 30px;
left: 60px;
overflow: auto;
}

然后 JavaScript 就非常简单了:

// Execute after DOM has loaded
window.onload = function() {
var postIt = document.getElementsByClassName('post-it'),
addTextToNote = function () {
//"this" is the textarea because the function is bound to the textarea;
var note = this.parentNode,
postIt = note.parentNode;
note.removeChild(this);
note.innerText = this.value;
postIt.onclick = addTextArea;
},
addTextArea = function addTextArea() {
//"this" is the div with class "post-it" because the function is bound to it;
var note = this.getElementsByClassName('note'),
t = null,
i = 0;
for (i = 0; i < note.length; i += 1) {
t = document.createElement('textarea');
t.rows = 10; // 10 rows and 25 columns is about
t.cols = 25; // the correct size for the image
t.value = note[i].innerText; // add any existing text
t.onblur = addTextToNote;
note[i].appendChild(t); // add textarea to note
this.onclick = null; // remove click handler to prevent multiple click problems
t.focus(); // give focus to the textarea
}
},
i = 0;
for (i = 0; i < postIt.length; i += 1) {
postIt[i].onclick = addTextArea;
}
};​

请注意,在生产环境中,我也可能会为此使用 jQuery,因为我发现 DOM 操作的语法要简单得多(而且它是跨浏览器的,与上面的示例不同)。

这是一个 jsFiddle 演示:http://jsfiddle.net/gWf5Z/

关于javascript - 在 img 上动态添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14002803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com