Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击按钮本身时更改按钮背景色_Javascript_Jquery_Css_Ajax - Fatal编程技术网

Javascript 单击按钮本身时更改按钮背景色

Javascript 单击按钮本身时更改按钮背景色,javascript,jquery,css,ajax,Javascript,Jquery,Css,Ajax,假设我有一个带有给定背景图像的#按钮:url(图像/某些背景),我想在单击它时将其更改为另一个背景,比如url(图像/其他背景) 略去主题,但应该考虑使用精灵,而不是2个完全分离的图像。 为什么??由于连接速度较慢,在某些浏览器上,当下载然后加载新图像时,单击事件将导致“闪烁”。精灵将看到图像已加载,因此您只需将背景位置更改为“加载”新图像。尝试以下操作: $(“#按钮”).css(“背景图像”,“url(/images/otherbackground.png)”) 或 $(this.css(“

假设我有一个带有给定背景图像的#按钮:url(图像/某些背景),我想在单击它时将其更改为另一个背景,比如url(图像/其他背景)


略去主题,但应该考虑使用精灵,而不是2个完全分离的图像。

为什么??由于连接速度较慢,在某些浏览器上,当下载然后加载新图像时,单击事件将导致“闪烁”。精灵将看到图像已加载,因此您只需将背景位置更改为“加载”新图像。

尝试以下操作:

$(“#按钮”).css(“背景图像”,“url(/images/otherbackground.png)”)

$(this.css(“背景图像”,“url(/images/otherbackground.png)”)

这对我有用

CSS

只是为了看得更清楚

代码

显然,您需要为自己切换图像

如果您遇到问题,请检查

  • 首先调用jQuery脚本,然后再调用该脚本

  • 您的图像路径是否正确


  • 设置sprite需要一些学习。但我同意,这是最好的方式,我认为他的具体问题与他没有阻止他的超链接违约事件有关。在对一个删除的答案的评论中,他说他把它改成了一个按钮,它就起作用了。上面的评论把它钉住了。回到我的原始代码,它神奇地工作了。还有一个问题,我将如何永久性地更改按钮的背景图像,这样,如果我重新加载页面,“其他背景”就会出现。您可以使用HTML5本地存储()存储状态,然后在页面加载时查询该状态?
            HTML
    
             <a id="button" ></a> 
    
            CSS
    
         display: block; 
         height:100px;
         width:100px;
         background-image:url(images/other_background.png)
    
        $(document).ready(function(){
    
        $('#button').click(function(){
    
                $('#button').css('backgroundImage', 'url(images/other_background.png)');
    
            });
    
    });
    
    #button{display: block; height:100px; width:100px;  
    background-image:url(http://cheeptalk.files.wordpress.com/
    2009/05/smurfs-hefty-smurf-100x100.png?w=96&h=96); border:1px solid red;}
    
    $('#button').click(function(){
        $(this).css('backgroundImage','url(http://images.mirror.co.uk/upl/m4/\
        feb2010/9/3/mr-t-100x100-938742195.jpg)');
    });