简体   繁体   English

更改正文背景

[英]Change body Background

I want to change background image of my body when I click a button. 我想在单击按钮时更改身体的背景图像。

My html code lets is 我的html代码让是

<body id = "body">

    <input type = "button" id = "button" value = "Change Background" onclick  = "Background_change()"></input>

</body>

My CSS code is 我的CSS代码是

body {
    background-image : url('20a.jpg');
    font: 18px Arial ;
    color : white;
}

Java Script Java脚本

I tried to change the image using JavaScript function using following code 我尝试使用以下代码使用JavaScript函数更改图像

function Background_change()
{
    var imager = document.getElementById("body").style.backgroundImage;
    imager.style.backgroundImage = url("20a.jpg");
}
document.body.style.backgroundImage = "url('yourNewImage.jpg')"

You need to: 你需要:

  1. Reference the element, not the style property. 引用元素,而不是style属性。
  2. Use quotes ' before and after the value. 在值之前和之后使用引号'

Change the code like this: 像这样更改代码:

function Background_change()
{
    var imager = document.getElementById("body");
    imager.style.backgroundImage = 'url("20a.jpg")';
}

Try this: 尝试这个:

  1. first get the variable of body 首先获取身体的变量
  2. then give link of image with ' or "". 然后用'或“”给出图像的链接。

 function Background_change(){ var imager = document.getElementById("body"); imager.style.backgroundImage = "url(http://im.rediff.com/money/2013/may/06car5.jpg)"; } 
 <body id="body"> <input type="button" id="button" value="Change Background" onclick="Background_change()"></input> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM