请检查这个JSFiddle ,这里有两个名为step-wrapper
的div,在这些step-wrapper
div中有三个名为step-box
的div。它的编写方式是,当单击 step-box
div 时,其背景颜色会变为黄色。
我添加了一个重置按钮。我需要的是点击重置按钮,最后点击的 step-box
div 的颜色应该变为白色。但是在这段代码中,当我点击重置按钮时,所有步骤框的背景颜色都会变为白色。
最佳答案
我相信这就是您要找的: https://jsfiddle.net/richardgirges/8m9qstg3/11/
我们正在保存对 lastClicked
div 的引用,并在点击 reset
时专门针对它。像这样:
var $lastClicked = null;
$('.step_wrapper').on('click','.step_box',function () {
$(this).parent().find('.step_box').css('background-color', '');
$(this).css('background-color', '#fff000');
$lastClicked = $(this);
});
$('.reset').on('click',function(){
if ( $lastClicked ) {
$lastClicked.css( 'background-color', '#fff' );
$lastClicked = null;
}
});
编辑:改进了代码。使用显式 var
实例化将其保持在范围内。
关于javascript - 如何更改 css 背景 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30714471/