javascript 的 div.style.backgroundImage,直接设置为img(Image)
functionsetbg(){vartop=document.getElementById("thetop");varimg=newImage();img.src="b...
function setbg() {
var top = document.getElementById("thetop");
var img = new Image();
img.src = "bar_bg.png";
img.style.width = top.style.width;
img.style.height = top.style.height;
top.style.backgroundImage = img;
}
我想加载图片,设置好宽高,再设置div的背景,但是
top.style.backgroundImage = img;
这句应该怎么写呢?求教~ 展开
var top = document.getElementById("thetop");
var img = new Image();
img.src = "bar_bg.png";
img.style.width = top.style.width;
img.style.height = top.style.height;
top.style.backgroundImage = img;
}
我想加载图片,设置好宽高,再设置div的背景,但是
top.style.backgroundImage = img;
这句应该怎么写呢?求教~ 展开
3个回答
展开全部
function setbg() {
var top = document.getElementById("thetop");
var img = new Image();
img.src = "bar_bg.png";
img.width = top.style.width;
img.height = top.style.height;
img.onload = function (top) {
top.style.backgroundImage = "url(bar_bg.png);";
}
}
更多追问追答
追问
不行啊,背景图片没显示
追答
<!DOCTYPE HTML>
<html>
<head>
<meta charset=UTF-8 />
<title>Nothing</title>
<style type="text/css">
#thetop {
width: 600px;
height: 800px;
}
</style>
<script>
function setbg ()
{
var top = document.getElementById ("thetop");
var img = new Image ();
img.src = "pic.jpg";
img.width = top.clientWidth;
img.height = top.clientHeight;
img.onload = function ()
{
top.style['background-image'] = "url(pic.jpg)";
top.style.backgroundSize = "600px";
document.body.appendChild (img);
}
}
</script>
</head>
<body>
<div id="thetop">dd</div>
<input type="button" value="setbg" onclick="setbg ();" />
</body>
</html>
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
//图片的异步加载需要进行兼容性判断
var _img = new Image();
_img.src = src;
if(_img.complete){
//some fun...
}else{
_img.onload = function(){
//some fun...
};
}
var _img = new Image();
_img.src = src;
if(_img.complete){
//some fun...
}else{
_img.onload = function(){
//some fun...
};
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
top.style.backgroundImage = "url(bar_bg.png)";
追问
那这样子图片的宽高呢?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询