如何在点击时更改CSS背景图片? [英] How to change css background-image on click?

查看:125
本文介绍了如何在点击时更改CSS背景图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当某人单击按钮时,我想更改css背景图像:".

I'd like to change the css "background-image:" when someone clicks a button.

我不确定是否可以通过CSS进行更改,或者是否需要合并Java脚本.另外,如果我需要Java脚本,我需要哪种类型的代码?

I'm not sure if I'm able to change it through css or if I would need to incorporate java script. Also, if I need java script what type of code would I need?

我当前的解决方法是使用CSS,它看起来像:

My current work around is with css and it looks like:

.hello-button {
background-image: url("hello.png");
background-repeat: no-repeat;
background-attachment: inherit;
background-position: center;
-webkit-transition: 2s ease-out;
-moz-transition: 2s ease-out;
-o-transition: 2s ease-out;
transition: 2s ease-out;
}

.hello-button:hover {
background-image: url("bye.png");
background-repeat: no-repeat;
background-attachment: inherit;
background-position: center;
transition-delay: .7s;
-webkit-transition-delay: .7s;
-moz-transition-delay: .7s;
-o-transition-delay: .7s;
}

推荐答案

我会这样处理. http://jsfiddle.net/darcher/6Ex7h/

jquery

   $('.img').on({
    click: function(){
        $(this).addClass('new-bg').removeClass('bg') // changes background on click
    },
    mousedown: function() {
        // :active state
    },
    mouseup: function() {
        // on click release
    },
    mouseenter: function() {
        // on hover
    },
    mouseleave: function() {
        // hover exit
    }
    /* 
      , hover: function(){
           // or hover instead of enter/leave
        }
    */
})

在这些变化的状态下,您可以执行所需的任何操作.您还可以使用 http://api.jquery.com/category/events/mouse-events/

With these varying states, you can do anything you need. There are also a variety of other states you can use http://api.jquery.com/category/events/mouse-events/

html

<div href="#" class="img bg"></div>

css

.img{
    background-repeat:no-repeat;
    background-size:cover;
    background-position:center;
    display:block;
    height:200px;
}
.bg{
    background-image:url(http://placehold.it/300x200/white/black);
}
.new-bg{
    background-image:url(http://placehold.it/300x200/black/white);
}

仅有css替代方案,但它们在支持方面并不是很好:

there are css only alternatives, but they're not really great on support: http://tympanus.net/codrops/2012/12/17/css-click-events/

这篇关于如何在点击时更改CSS背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆