Noob here - I'm working on a simple Javascript calculator, and I'm using lists (li) for buttons. I want the li backgroun开发者_如何学运维d-color to change onClick, but then automatically change back half a second later. So basically I want the button click to flash the new color, not toggle it.
Is this possible?
Edit: This is what I have in my header now, but it's still not working:
$(li).click(function() {
var $elem = $(this);
var oldBG = $elem.css('backgroundColor'));
$elem.css('backgroundColor', '#FFFFFF').delay(1000).css('backgroundColor', oldBG);
});
and my li tags:
<li class="key" onClick="calc('7')">7</li>
$('.key').click(function() {
// make a jQ collection of the DOM element from the event
var $elem = $(this);
// store the background-color
var oldBG = $elem.css('background-color');
// change the background color to what you want
$elem.css('backgroundColor', '#FF0000');
// after 1 second, change it back
setTimeout(function() {
$elem.css('background-color', oldBG);
}, 1000);
});
working sample
jQuery-UI will animate color values using the jquery-color plugin, if you're into that
Sure is possible!
Check out the documentation for setTimeout()
Here's a link to get you started.
http://www.w3schools.com/js/js_timing.asp
If you are willing to change your markup so that each button is an <a> element (perhaps inside those li elements), you can use
a:active {
To change the way the buttons look when pressed. http://www.w3schools.com/CSS/css_pseudo_classes.asp
You can add a background color style to the element when clicked, and use the setTimeout
function to remove it later:
$(function(){
$('li').click(function(){
var e = $(this);
e.css('background-color', 'red');
window.setTimeout(function(){
e.css('background-color', '');
}, 500);
});
});
(Note: There is a delay
method in jQquery, but that is intended to be used with animation, not as a replacement for setTimeout
.)
Working example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="sv" xml:lang="sv">
<head>
<title>Test</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('li').click(function(){
var e = $(this);
e.css('background-color', 'red');
window.setTimeout(function(){
e.css('background-color', '');
}, 500);
});
});
function calc(digit) {
var lcd = $('#lcd');
lcd.text(lcd.text() + digit);
}
</script>
</head>
<body>
<div id="lcd"></div>
<ul>
<li class="key" onClick="calc('1')">1</li>
<li class="key" onClick="calc('2')">2</li>
<li class="key" onClick="calc('3')">3</li>
<li class="key" onClick="calc('4')">4</li>
<li class="key" onClick="calc('5')">5</li>
<li class="key" onClick="calc('6')">6</li>
<li class="key" onClick="calc('7')">7</li>
<li class="key" onClick="calc('8')">8</li>
<li class="key" onClick="calc('9')">9</li>
<li class="key" onClick="calc('0')">0</li>
</ul>
</body>
</html>
精彩评论