开发者

load file on hover using jQuery

I want to load an external file (using jQuery) when the user hovers a div. I tried loading it like a css file on hover but no luck. (Also, I can load a css file on hover, right? That code I tried for that is below.)

$(document).ready(function () 开发者_Go百科{
    $("#f1_container2").hover(function () {
        $('head').append('<link rel="stylesheet" href="theme/supersized.shutter.css" type="text/css" media="screen" />');
    });
});


You can load content using $(".target").load("file.html"), where file.html is an HTML fragment containing some markup.

Since CSS is passive (it doesn't do anything until someone uses it), it can sit in the head in the first place. That way, when you hover over a div, you can do $(".target").addClass("newClass") to apply some groovy styling.

hover() can also take a SECOND function, which is invoked when the mouse leaves the target, so you can undo whatever you did on the mouseover.


The document has already been loaded and rendered when you append the code for the stylesheet. The browser has already retrieved the needed resources and won't retrieve a file because you appended some code.

I would recommend, as mentioned, pre-loading your images or using another technique to retrieve the file on hover.

I believe something like this may work.

$(document).ready(function () {
    $("#f1_container2").hover(function () {

         // The easy way
         //$('head').append('<img src="images/sprite.gif">');

         // The cool way
         var $img = $('<img>', {
             src:    'images/sprite.gif',
             load:   function() {
                 $(this).fadeIn('slow');
             },
             css: {
                 display:  'none'
             }    
         }).appendTo('body'); // append to where needed
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜