简体   繁体   中英

How to bring drop shadow effect for a div on mouseover using jQuery / Javascript

I have many divs in an html page. I need to give these divs a drop shadow effect on mouseover using jQuery/Javascript. I can get it work if the drop shadow is to be applied initially but I am not able to get it work at the run time.

The divs which needs to have shadow applied has a common class. In the fiddle it is test.

I have created a fiddle

http://jsfiddle.net/bobbyfrancisjoseph/ZEuVE/2/

It should work on IE8 and above and so I guess CSS3 can be used.

use this css for the shadow effect (covers most browsers):

.classWithShadow{
   -moz-box-shadow: 3px 3px 4px #000; 
   -webkit-box-shadow: 3px 3px 4px #000; 
   box-shadow: 3px 3px 4px #000; 
}

use the following jquery:

$(".yourDiv").hover(function()
{ 
   $(this).toggleClass('classWithShadow');
});

Complete code here: http://jsfiddle.net/ZEuVE/3/

EDIT: sorry , I editted your initial fiddle instead of making a new one. But it works ^^ :)

CSS3 shadow is not supported by IE8

For your Above IE8 and other browsers

$("div").hover(function() {
        $(this).css(
            "box-shadow", "10px 10px 5px #888"
        );
    }, function() {
        $(this).css(
            "box-shadow", "0px 0px 0px #888"
        );
    });
$("div").mouseover(function() {
     $(this).css("box-shadow", "5px 5px 5px #555");
  }).mouseleave(function(){
    $(this).css("box-shadow", "0px 0px 0px #555");
 });

OR use mouseenter event

$("div").mouseenter(function() {
   $(this).css("box-shadow", "5px 5px 5px #555");
  }).mouseleave(function(){
    $(this).css("box-shadow", "0px 0px 0px #555");
});

There is little point in using jQuery to add simple hover effects when the CSS :hover psuedo-class works perfectly on its own.

The only problem you have is that IE8 does not support native CSS drop-shdows (box-shadow).

To overcome this you have two choices;

1) Attempt to coax microsoft's proprietary DropShadow and Blur filters into producing something resembling a drop-shadow. It's possible, as this guide shows, but in my experience using MS's filters is your first step on the path to a life filled with misery and pain. Filters affect other, seemingly unrelated styles and elements on the same page in ways that it is impossible to foretell. All you can really do is try it and see.

2) use an image. This is pretty bad, and is tricky to get the image right if the divs are all different sizes. But if you do it in an IE8 only style sheet and know the dimensions beforehand, it can work well.

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