HTML - 如何在 OnClick 事件上更改按钮背景颜色


HTML - How to change button background color on OnClick event

>我有以下PHP代码,其中4个按钮从数据库表中动态显示。根据单击的按钮在页面上显示不同的内容。

现在,我想在单击第一个按钮时这样做,然后应该更改按钮 bg 颜色,以便访问者可以知道按下了哪个按钮。单击第二个按钮时,应更改该按钮的 bg 颜色,并且以前单击的按钮(本例中的第一个按钮(应恢复为原始颜色。

请让我知道使用CSS或Javascript执行此操作的最简单方法。

<form name="frm_list" action="toptipper.php" method="post" enctype="multipart/form-data">
<?php 
while(!$rs_tab_list->eof())
{
?>
<button type="submit" name="btn_tab" value="<?php print($rs_tab_list->fields("tabpkid")); ?>"><?php print($rs_tab_list->fields("title")); ?></button>
<?php  
$rs_tab_list->movenext();
}       
?>
</form>

如果一次只选择一个注释标记,请取消注释。

$('button').on("click",function(){  
  //$('button').not(this).removeClass();
  $(this).toggleClass('active');
  
  });
.active{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>

这样编写 JS Onclick事件onclick="this.style.backgroundColor = 'red';"

<?php 
while(!$rs_tab_list->eof())
{
?>
<button type="submit" name="btn_tab"  onclick="this.style.backgroundColor = 'red';" value="<?php print($rs_tab_list->fields("tabpkid")); ?>"><?php print($rs_tab_list->fields("title")); ?></button>
<?php  
$rs_tab_list->movenext();
}       
?>
我不知道

像这样更改按钮颜色是否是最好的设计决策,但以防万一纯粹出于学习目的:

1(给2个按钮不同的ID

2(使用此JavaScript代码

b1.onclick = function() {
     b1.style.background = "green";
     b2.style.background = "";   }
b2.onclick = function() {
     b1.style.background = "";
     b2.style.background = "green";  }

现场示例:

JS小提琴 - 单击按钮,查看颜色如何变化

$('button').on("click",function(){  
  //$('button').not(this).removeClass();
  $(this).toggleClass('active');
  
  });
.active{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>

将id添加到按钮,然后像这样:

$('#buttonID').css('background-color','coloryouwant');
如果你想

恢复上一个按钮的初始值,一个简单的方法是使用jQuery。你可以使用 addClass(( 例程来实现这一点。例如:

//Restore all values
$("input").removeClass();
$("input").addClass("default");
//Set class that has the highlight color
$("#button2").addClass("highlight");

使用此 HTML:

<input type="button" id="button1"/>
<input type="button" id="button2"/>

而这个 CSS:

.default { background-color: blue;}
.highlight { background-color: yellow;}

只需将 onClick 添加到元素即可调用正确的函数。

希望对您有所帮助。

jquery非常直接。我建议使用 jquery 添加类并稍后设置按钮样式。下面的小提琴可以帮助你。

http://jsfiddle.net/kiranvarthi/oudkau4j/

$("button").click(function(){ 
    $(this).addClass("active");
});
你可以

使用 js。创建类.active并在 css 中定义它:

.active {
    background-color: #yourcolor;
}

现在使用 js jquery,您可以创建 onclick 事件并在单击按钮上添加类:

$('#yourbtnid').click(function() {
    $(this).addClass('active');
}

!不要忘记在js文件或html文件中的代码之前导入jquery库

按钮中你可以调用一个jquery函数,如

<input type="button" onClick=colorchange();>

/* 在 jquery 函数中你可以这样做。

function colorchange(){
$(this).css('background-color','#000000');
}