Javascript jquery onclick 更改 css 背景图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14619267/
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-24 17:25:21  来源:igfitidea点击:

jquery onclick change css background image

javascriptjqueryhtmlcss

提问by sandeep

am using this code to get menu tab.when i mouseover on the tab the tab image will change, similarly i want to change the image of tab onlick using jquery.i used the below code to do this but i was not able to get it.how can i do this.

正在使用此代码获取菜单选项卡。当我将鼠标悬停在选项卡上时,选项卡图像将更改,同样我想使用 jquery 更改选项卡 onlick 的图像。我使用下面的代码来执行此操作,但我无法获得它。我怎样才能做到这一点。

<html>
    <head>
    <title>Css Menu</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <style>
    .home {
        background: url("images/tab2.png") repeat scroll 0 0 transparent;
        border-radius: 4px 4px 0 0;
        height: 75px;
        left: 54px;
        position: relative;
        top: 25px;
        width: 90px;
    } 
    .home:hover {
        background: url("images/tab3.png") repeat scroll 0 0 transparent;
        border-top: 1px solid black;
        border-left: 1px solid black;
        border-right: 1px solid black;
    }


    </style>
    <script type="text/javascript">
        $(function() {
              $('.home').click(function() {
                    $('home').css('backgroundImage', 'url(images/tabs3.png)');
              });
        }):
    </script>

    </head>
    <body><div class="frame">
    <div class="header1"></div>
    <div class="header2">
        <a href="#"><div class="home" onclick="function()"><img src="images/tools.png" class="image"><br><span class="align">Home</span></div></a>
        </div>
    <div class="header3"></div>
    </div>
    </body>
    </html>

回答by sandeep

You need to use background-imageinstead of backgroundImage. For example:

您需要使用background-image而不是backgroundImage。例如:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

回答by Jai

I think this should be:

我认为这应该是:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

并删除这个:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

你必须 make sure you have a correct path to your image.

回答by Dineshkani

Use your jquery like this

像这样使用你的 jquery

$('.home').css({'background-image':'url(images/tabs3.png)'});