Changing the background color of a <div> section

霸气de小男生 提交于 2019-12-20 03:53:17

问题


I'm trying to use jQuery to change the background color of a <div> section when pressing on a button, and below is the code to do that. Why isn't it working?

HTML file

<html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="script.js"></script>
<style type="text/css"> 
#name{
background-color: #FFFFF2;
width: 100px;
}
</style>
</head>
<body>
<input type="button" id="bgcolor" value="Change color"/>
<div id="name">
Abder-Rahman
</body>

</html>

script.js

$("bgcolor").click(function(){
    $("#name").animate(
        {backgroundColor: '#8B008B'},
        "fast");}
);

Thanks.


回答1:


You have several problems:

  1. Your selector is wrong: $("#bgcolor")
  2. You're missing a closing </div> tag.
  3. You need jQueryUI to animate background-color.

HTML:

<input type="button" id="bgcolor" value="Change color"/>
<div id="name">
Abder-Rahman
</div>

JS:

$("#bgcolor").click(function(){
    $("#name").animate(
        {backgroundColor: '#8B008B'},
        "fast");}
);

Your code, fixed (and working with jQueryUI included): http://jsfiddle.net/andrewwhitaker/rAVj9/




回答2:


From the jQuery website:

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.)

Use jquery UI package to animate colors.




回答3:


Ensure you include the CSS selector inside the jQuery that you wish to target.

$("bgcolor").click(function(){

Should be:

$("#bgcolor").click(function(){

Because you are targeting an ID.



来源:https://stackoverflow.com/questions/7622170/changing-the-background-color-of-a-div-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!