简体   繁体   中英

Change the style of a div with javascript and jquery

In my source I have: In the style section:

<head>
        <style>
               .grayableDiv{background-color:transparent}
        </style>
    </head>

<script>
            function DoGrayEffectIn()
            {
                $('.grayableDiv').css('background-color', 'Gray');

            }
            function DoGrayEffectOut()
            {
                $('.grayableDiv').css('background-color', 'Transparent'); 
            }
       </script>

<div class="grayableDiv" onmouseover ="DoGrayEffectIn" onmouseout="DoGrayEffectOut">

But I cannot see the effect when going with the mouse over the div. What am I doing wrong. Is it possible to mix jquery and javascript in this way?

You need to add parenthesis () to your event handlers so their functions gets called.

Should be onmouseover ="DoGrayEffectIn()" , not onmouseover ="DoGrayEffectIn"

Stack snippet

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <head> <style> .grayableDiv { background-color: transparent } </style> </head> <script> function DoGrayEffectIn() { $('.grayableDiv').css('background-color', 'Gray'); } function DoGrayEffectOut() { $('.grayableDiv').css('background-color', 'Transparent'); } </script> <div class="grayableDiv" onmouseover="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">div</div> 


A better practice for attaching JavaScript to the front-end of a website is to separate it from the markup, often referred as unobtrusive javascript .

Stack snippet

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <head> <style> .grayableDiv { background-color: transparent } </style> </head> <script> $(document).ready(function() { $('.grayableDiv') .mouseover(function() { $(this).css('background-color', 'Gray'); }).mouseout(function() { $(this).css('background-color', 'Transparent'); }); }); </script> <div class="grayableDiv">div</div> 

您没有使用()调用该函数

<div class="grayableDiv" onmouseover ="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">

Another cleaner way without mixing the JavaScript with the Html

<script>
$(document).ready(function(){
    $(".grayableDiv").mouseover(function(){
        $(".grayableDiv").css("background-color", "gray");
    });
    $(".grayableDiv").mouseout(function(){
        $(".grayableDiv").css("background-color", "transparent");
    });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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