简体   繁体   English

使用jQuery在悬停时加载文件

[英]load file on hover using jQuery

I want to load an external file (using jQuery) when the user hovers a div. 我想在用户悬停div时加载外部文件(使用jQuery)。 I tried loading it like a css file on hover but no luck. 我试图像悬停时的css文件一样加载它,但是没有运气。 (Also, I can load a css file on hover, right? That code I tried for that is below.) (此外,我可以在悬停时加载css文件,对吗?我在下面尝试过的代码。)

$(document).ready(function () {
    $("#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. 您可以使用$(“。target”)。load(“ file.html”)加载内容,其中file.html是包含某些标记的HTML片段。

Since CSS is passive (it doesn't do anything until someone uses it), it can sit in the head in the first place. 由于CSS是被动的(除非有人使用它,否则它不会做任何事情),因此它可以首先放在头部。 That way, when you hover over a div, you can do $(".target").addClass("newClass") to apply some groovy styling. 这样,当您将鼠标悬停在div上时,可以执行$(“。target”)。addClass(“ newClass”)以应用一些常规样式。

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. hover()也可以采用SECOND函数,当鼠标离开目标时会调用该函数,因此您可以撤消对鼠标悬停所做的任何操作。

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
    });
});

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

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