Html 单击 javascript 更改背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15323323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:18:38  来源:igfitidea点击:

On click javascript change background image

javascriptcsshtml

提问by zaporojan

Hello i have a problem with some javascript. I have a div to layout a button who does something(in my chase it will insert number 1 in to a box) and i want to change the background of the button when clicked:

你好,我有一些 javascript 的问题。我有一个 div 来布局一个按钮,它会做某事(在我的追逐中,它会将数字 1 插入到一个框中),我想在单击时更改按钮的背景:

<div id="nr1"><INPUT TYPE="button" NAME="one"   OnClick="this.style = 'background-image:URL(images/totalback.gif);'; Calc.Input.value += '1'" style="width:45px; height:30px; background-color:transparent;  border-style: none; border-width: 0px 0px 0px 0px"></div>

This is the code,but it ignores my background image change. Can any one help me? Short info: i have little clue about javascript.

这是代码,但它忽略了我的背景图像更改。谁能帮我?简短信息:我对 javascript 一无所知。

Thank you anyway.

还是很感谢你。

回答by Iesus Sonesson

When using javascript you do it like this:

使用 javascript 时,您可以这样做:

this.style.backgroundImage="url()";

Note that javascript changes the syntax a bit, instead of background-image you use backgroundImage.

请注意,javascript 稍微更改了语法,而不是使用 backgroundImage 的背景图像。

回答by iConnor

Why dont you just use jquery its simple like this

你为什么不直接使用 jquery,就像这样简单

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#nr1 input').on("click", function(){
         $(this).css({'background' : 'red'});
      });
   });
</script>

http://api.jquery.com/css/

http://api.jquery.com/css/

回答by Chandra Sekhar

I hope you can use something like this in css:

我希望你可以在 css 中使用这样的东西:

#your_btn_id{
    width:200px;
    height:50px;
    background-image: url('../images/inactive.png');
}

When clicked change the background image:

单击时更改背景图像:

#your_btn_id:active{
    background-image: url('../images/active.png');
}

Hope it will work and the thing is its very simple to use.

希望它会起作用,而且使用起来非常简单。