Javascript 将图像转换为内容的背景
我遇到了一个问题,我试图用脑海中浮现的唯一方式来解决它。问题是,我试图获取附加到图像按钮的内容,但当用户将鼠标悬停在按钮上时,该内容被隐藏,并在按钮旁边显示背景图像。当问题出现时,我将背景图像当前作为一个图像(img标记),因此我可以通过调整高度/宽度来拉伸它。我希望能够将内容放在该图像的顶部:例如:Javascript 将图像转换为内容的背景,javascript,jquery,css,Javascript,Jquery,Css,我遇到了一个问题,我试图用脑海中浮现的唯一方式来解决它。问题是,我试图获取附加到图像按钮的内容,但当用户将鼠标悬停在按钮上时,该内容被隐藏,并在按钮旁边显示背景图像。当问题出现时,我将背景图像当前作为一个图像(img标记),因此我可以通过调整高度/宽度来拉伸它。我希望能够将内容放在该图像的顶部:例如: <div class="ContentDiv"><img id="ContentButton"> <ul class="Content"><li>t
<div class="ContentDiv"><img id="ContentButton">
<ul class="Content"><li>this is first</li><li> This is second</li>
<li>This is third content part</li></ul></div>
<div class="ContentDiv"><img id="ContentButton2">
<ul class="Content"><li>this is first</li><li> This is second</li>
<li>This is third content part</li></ul></div>
<div id="backgroundDiv"><img id="backgroundimg" src="backgroundI_Want_To_Use"></div>
上面做的是意图,也就是在div img之后添加所有的内容,这就是我要解决的问题,我希望能够使background img标记成为内容的实际背景。如果我尝试将css中的背景图像设置为div的url,则该图像不会使背景足够大。请记住,我在某些情况下处于ie 6状态,但在大多数情况下,我仅处于ie 8状态
因此,我尝试使用css更改图像和内容的z索引,但不起作用:
#backgroundimg{
z-index:-100;
position:absolute;
}
.Content{
z-index:100;
position:relative;
}
如果你没有使用糟糕的浏览器,css3可以帮你一把
background-size: [ [ <length> | <percentage> | auto ]{1,2} || round ]
background size:[[| | auto]{1,2}| | round]
我会使用不同的方法。 按如下方式组织内容:
+ DIV (position static / relative)
+ IMG (position relative)
+ DIV (position absolute)
+ "contents"
所以如果我理解这个问题,你可以不用任何JS来工作。。。请参见此处的示例:
$(文档).ready(函数(){
var img=$(“#backgroundDiv”).html();
$(“.ContentDiv”).mouseover(
函数(){
$(“#backgroundDiv”).html(img++'+$(this.find(“.Content”).html()+”);
/*如果要将“背景”图像缩放到内容,请使用以下行*/
$(“#backgroundDiv”).css('height',$(this.find(“.Content”).height());
});
});
#背景{
位置:相对位置;
高度:自动;
宽度:自动;
}
#背景{
宽度:100%;
身高:100%;
}
.补充内容{
位置:绝对位置;
排名:0;
左:0;
z指数:999;
}
使用悬停部分:-需要是锚元素才能在IEi中工作我已经更新了我的示例以使用悬停。这在IE7和IE8中都是有效的。这对我来说很有效,我只是需要稍微改变一下,以适应我的问题。也适用于所有浏览器
+ DIV (position static / relative)
+ IMG (position relative)
+ DIV (position absolute)
+ "contents"
<script type="text/javascript">
$(document).ready(function(){
var img= $("#backgroundDiv").html();
$(".ContentDiv").mouseover(
function(){
$("#backgroundDiv").html(img+'<div class="addedContent">'+$(this).find(".Content").html()+'</div>');
/* Use the following line if you want to scale the "background" image to the content */
$("#backgroundDiv").css('height',$(this).find(".Content").height());
});
});
</script>
<style type='text/css'>
#backgroundDiv{
position:relative;
height:auto;
width:auto;
}
#backgroundimg{
width:100%;
height:100%;
}
.addedContent{
position:absolute;
top:0;
left:0;
z-index:999;
}
</style>