【发布时间】:2015-11-08 05:34:29
【问题描述】:
当我将鼠标悬停在图像上时,该图像上会出现一些文字。但是,居中后,定位出现问题,文字标题显示在图像的左侧,也没有居中。
以下是我的代码,其中包含在互联网上找到的几段代码。
这是我的 HTML:
<div class="col-md-3">
<p class="caption">
<img class="profile_pic" src="img/spiropoulos.jpg" alt="spy" />
<span>Rainbow and Tree</span>
</p>
</div>
CSS:
div.clear {
clear: both;
}
p.caption {
display: block !important;
position: relative !important;
}
p.caption img {
position: absolute !important
}
p.caption span {
background: #000;
background: rgba(0,0,0,0.8);
color: white !important;
display: none;
padding: 5px 10px !important;
text-align: center;
position: absolute !important;
bottom: 0 !important;
left: 0 !important;
width: 100% !important;
}
p.caption span big {
font-weight: bold;
}
.profile_pic{
height: 160px;
width: 200px;
}
和 JS:
// this is to center the image
$("p.caption>img").each(function(i, img) {
$(img).css({
position : "relative",
left : ($(img).parent().width() / 2) - ($(img).width() / 2)
});
});
// this is for the caption
// For each instance of p.caption
$("p.caption>div").each(function() {
$(this)
// Add the following CSS properties and values
.css({
// Height equal to the height of the image
"height" : $(this).children("img").height() + "px",
// Width equal to the width of the image
"width" : $(this).children("img").width() + "px"
})
// Select the child "span" of this p.caption
// Add the following CSS properties and values
.children("span").css(
// Width equal to p.caption
// But subtract 20px to callibrate for the padding
"width", $(this).width() - 20 + "px")
// find the <big> tag if it exists
// And then add the following div to break the line
.find("big").after('<div class="clear"></div>');
// When you hover over p.caption
$("p.caption>div").hover(function() {
// Fade in the child "span"
$(this).children("span").stop().fadeTo(400, 1);
}, function() {
// Once you mouse off, fade it out
$(this).children("span").stop().delay(600).fadeOut(400);
});
// End $(this)
});
预期结果是这样的:http://css-plus.com/examples/2010/05/how-to-create-an-image-caption-with-jquery/
【问题讨论】:
-
由于您将
div嵌套在p中,这在技术上是HTML 规范不允许的,因此p标记会过早关闭,并且您的标记不会按预期运行。将p替换为div,这可能会解决问题。 -
我认为您也可以主要在 CSS 中执行此操作...您在使用 Bootstrap 吗?
-
div元素不是p元素的有效子元素 -
@guest271314 你说的是JS代码?这是我最近的尝试,如果我使用
p.caption,它就不会再工作了。 -
好的,伙计们。我用期望的结果更新了我的问题。
标签: javascript jquery html css image