单击后如何更改颜色按钮

时间:2014-08-06 22:59:28

标签: javascript jquery css

我想在点击它之后改变按钮的颜色。我尝试过使用css和javascript,但它对我不起作用。 这是css代码

<style>
.style {
    width: 115px;
    height: 45px;
    background: #8CC639;
    padding: 15px;
    text-align: center;
    border-radius: 5px;
    color: #3071A9;
    font-weight: bold;
    cursor: pointer;
}

.style:hover {
background: blue;
}
 .style:active{
background: blue;

} */
.style:visited {
    color: red;
}

</style>

以下是我的jsp页面中的内容:

    <script>

    $(document).ready(function(){
        $('#btnHousing').click(function() {
            //Now just reference this button and change CSS
            $(this).css('background-color','#f47121');
        });
        $( "#tabs" ).tabs({
        beforeLoad: function( event, ui ) {
        ui.jqXHR.error(function() {
        ui.panel.html(
        "Couldn't load this tab. We'll try to fix this as soon as possible. " +
        "If this wouldn't be a demo." );
        });
        }
        });

    })(jQuery);
    </script>

    <div class="page">

    <fieldset>
    <form>

    <div align="center">
    <input  type = "button"
           value = "Throw"
         onclick = "javascript:location.href='throw.html';"
    />

    <span class="right">
    <input  type = "button" id="style"
           value = "User"
         onclick = "javascript:location.href='userAction.html'; "
    />
   </div>
        <div id="tabs">
            <ul>
                <li><a href="#tabs-1">Create</a></li>
            <!--    <li><a href="user/viewLogin.html">Log In</a></li> -->
                <li><a href="#tabs-2">Update</a></li>

            </ul>

            <div id="tabs-1">
                <h1>Create</h1>

            </div>
            <div id="tabs-2">
                <h1>Update</h1>
            </div>


        </div>

      </form>
      </fieldset>
    </div>

我想要像stackoverflow按钮。当用户点击按钮时,点击它后按钮的颜色会发生变化。我已经尝试过某种方式.css中的任何代码,JQuery ore javascript?谢谢!

4 个答案:

答案 0 :(得分:1)

您使用了类css选择器而不是id选择器。

将样式更改为

#style

而不是

.style

或更改按钮说

class="style"

答案 1 :(得分:1)

document.getElementById('id-of-the-button').onclick = function(){
    this.style.backgroundColor = '#ff0000';
};

或者

<style type="text/css">
  .red {background-color: #ff0000;}
</style>  

document.getElementById('id-of-the-button').onclick = function(){
  this.className = 'red';
};

答案 2 :(得分:1)

你可以试试这个:

var button = document.querySelector("button");
button.addEventListener("click", function() {
  document.body.classList.toggle("purple");
  //the purple is a css class
})

答案 3 :(得分:0)

您的点击处理似乎没问题。

似乎你没有一个id为“btnHousing”的按钮。

基于您的代码的经过测试的工作示例:

<input type="button" id="btnHousing" value="Housing"/>
<script>
    $('#btnHousing').click(function() {
        //Now just reference this button and change CSS
        $(this).css('background-color','#f47121');
    });
</script>