我遇到了一些问题,其中有大量带有消息框的内容页面。在这个消息框中,您可以有图像、文本、标题等。但是每个消息框的右上角都会有一个图标。如果我使用 position:absolute,图像将很好地位于框的顶部。但是,如果消息框有一个标题或一个段落,并且填充了框的宽度。文本将位于图像下方。
我基本上需要一个宽度的图像包装器,这样文本只会一直坐到图像的边缘。我 99% 确定我通过将绝对定位的图像包装在一个 div 中并赋予它一些样式,让它在 firebug 中工作。但我今天似乎无法让它工作!
有数百个页面,因此无法移动 HTML。该图像目前没有包装器。所以我不得不使用 Jquery 来包装图像。 (这就是答案)。
我知道绝对位置将元素置于文档流之外,但我能做些什么吗?
到目前为止,这是我的代码:
<div class="message">
<h3>Some text, a header perhaps? But this is the next that will sit under the image, sometimes it's a p tag.</h3>
<img class="messageIcon" src="/link-to-icon/which-are-the-same-size" border="0" width="64" >
<p>Some more random text that would appear in the messagebox this could go on for a few lines.</p>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('img.messageIcon').wrap('<div class="messageIconWrap" />');
alert("this is a test");
});
</script>
JS 在图像周围包裹了一个 div
CSS:
.messageIconWrap{
display: inline-block;
float:right;
height:60px;
width:60px;
}
div.message {
position: relative;
}
.message {
background: none repeat scroll 0 0 #393939;
clear: both;
}
.messageIcon {
position: absolute;
right: 20px;
top: 20px;
float: right;
}
JS fiddle - http://jsfiddle.net/jdp7E/
最佳答案
纯CSS解决方案:在容器开头添加伪元素
div.message:before { content:" "; float:right; width:75px; height:75px; }
在不支持生成内容的旧版浏览器中不起作用,因此主要是旧版 IE。对于那些容器的 padding-right 可以用作后备。
关于javascript - 在绝对定位元素周围环绕文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17211648/