简体   繁体   English

更改悬停颜色按钮单击

[英]change hover color button click

I want the div onhover background color to change to blue once button is clicked. 我希望div onhover背景颜色在单击按钮后变为蓝色。

In this example, it changes the normal background color as well: 在此示例中,它也更改了常规背景色:

 $(document).on("click", "button", function() { $(".box").on("mouseover", function() { $(".box").css("background", "blue") }); }) 
 .box:hover { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button>Change hover color</button> <hr/> <div class="box">Hello</div> 

Try 尝试

 $(document).on("click","button",function(){ $(".box").on("mouseover",function(){$(".box").css("background","blue")}); $(".box").on("mouseout",function(){$(".box").css("background","")}); }) 
 .box:hover{background:red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button>Change hover color</button> <hr/> <div class="box">Hello</div> 

make use of hover() jquery function and make use of class instead of css 利用hover() jQuery函数并利用类而不是CSS

$(".box").hover(function(){
    $(this).addClass("hover_me");
}, function(){
    $(this).removeClass("hover_me");
});

css class CSS类

.hover_me {
  background: blue;
}

Your Jquery DOM was incorrect, 您的Jquery DOM不正确,

Here is how it does 这是怎么做的

$(document).ready(function(){ $(document).ready(function(){

// jQuery methods go here... // jQuery方法在这里...

}); });

 $(function(){ $('button').click(function(){ $(".box").on("mouseover",function(){ $('.box').css("background","blue") }); $(".box").on("mouseout",function(){$(".box").css("background","") }); }) }); 
 .box:hover{background:red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Change hover color</button> <hr/> <div class="box">Hello</div> 

In your jQuery, add an eventhandler for mouseout, to remove the background. 在您的jQuery中,为mouseout添加事件处理程序,以删除背景。

$(document).on("click", "button", function () {
    $(".box").on("mouseover", function () {
        $(".box").css("background", "blue")
    });
    $(".box").on("mouseout", function () {
        $(".box").css("background", "none")
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM