我想在有人点击按钮时更改 css“background-image:”。
我不确定我是否能够通过 css 更改它,或者我是否需要合并 java 脚本。另外,如果我需要 java 脚本,我需要什么类型的代码?
我目前的工作是使用 css,它看起来像:
.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/
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 的替代品,但它们的支持并不是很好:http://tympanus.net/codrops/2012/12/17/css-click-events/
关于javascript - 如何在点击时更改 css 背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460031/