在图像 html 旁边键入文本

Type text next to an image html

本文关键字:文本 图像 html      更新时间:2023-09-26

我想在放置在图像右侧的contenteditable div中键入文本。

.HTML

<div class="container">
<div class="image">
    <img src="/path/*.jpg" alt="" />
</div>
<div class="text" contenteditable>
    <p></p>
</div>
<div class="clear"></div>

.CSS

.container {
    width: 1000px;
    border: 1px solid #000;
}
.image, .text {
    position: relative;
}
.image {
    width: 500px;
    height: 500px;
    overflow: hidden;
    float: left;
}
.text {
    min-height: 30px;
    border: 1px solid #000;
}
.clear{
    clear: both;
}

我的目标是在聚焦到contenteditable时将插入符号定位在图像的右侧,而不是像您在此小提琴中看到的那样定位到p tag的开头。

一种解决方案是在<p>中插入一个&nbsp;,如另一个小提琴所示,但这不是一个非常干净的解决方案:它会污染里面写的文本。

我可以利用JavaScript和jQuery,但纯HTML和CSS解决方案是首选。

有什么想法吗?

更新我忘了说文本也应该放在图像下方,这样它就不会浮动或隐藏

只需尝试左边距:500px;

.text {
    min-height: 30px;
    border: 1px solid #000;
    margin-left:500px;
}

您必须删除div 并应用于图像这些 css 样式:

display:    -moz-inline-stack;
display:    inline-block;
_overflow:  hidden;
*zoom:      1;
*display:   inline;

vertical-align: bottom;

将 overflow:hidden 添加到不应覆盖浮动元素的元素中:

http://jsfiddle.net/nothrem/0mdcLzqs/3/

<div class="container">
    <div class="image">
        <img src="https://ununsplash.imgix.net/photo-1417021423914-070979c8eb34?fit=crop&fm=jpg&q=75&w=1050" alt="" />
    </div>
    <div class="text" contenteditable style="overflow:hidden">
        <p></p>
    </div>
    <div class="clear"></div>
</div>

更新:您可以使用Javascript根据元素的内容更改溢出

document.getElementsByClassName('text')[0].onblur = function() {
    if (this.innerHTML.replace(/<[^>]+>/, '')) { //remove HTML tags
        this.style.overflow = 'visible';
    } else {
        this.style.overflow = 'hidden';
    }
}

完成编辑后,模糊触发,您可能需要添加其他事件,例如 onkeyup、onmouseclick 等。

除非

必要,否则我不是浮点数的忠实粉丝,我会从图像 CSS 中删除float: left并将这两行添加到.image, .text行中:

display: inline-block;
vertical-align: top;

获取图像下的文本

将容器宽度设置为图像的宽度,并使用向左或向右浮动设置文本的位置,如下所示:

.container {
  width: 500px; // width of image
  border: 1px solid #000;
}
 .image, .text {
 position: relative;
}
.image {
width: 500px;
height: 500px;
overflow: hidden;
float: left;
}
.text {
min-height: 30px;
width:100%;
border-top: 1px solid #000;
float:left;
text-align:center;  
}
.clear{
clear: both;
}

这是一个演示