在<a>

时间:2018-03-22 14:45:21

标签: html css hover

While I wasn't that concerned about it in the beginning, I noticed that my page size is about 9 MB (+/- 200 images). I want to somehow decrease this by only loading the image when the user hovers over the specific <a>, so that only that image is loaded (which should decrease the page size drastically).

The code below is what I'm using right now

<style>
div.img {
    display: none;
    position: absolute;
}

a:hover + div.img {
    display: block;
}
</style>

<div>
    <a href="/somename" target="_self" id="sid">Some Name</a>
    <div class="img">
        <img src="http://sub.domain.com/somename.jpg" alt="Some Name" style="some styles">
    </div>
</div>

I think it's possible with jQuery, but I don't know where to start.

Thanks in advance.

3 个答案:

答案 0 :(得分:1)

如果您的目录中有大约200个图像,当客户端请求网页时,如果您使用单页面布局,则必须下载图像以准备它们。就像亚当说的那样,我会研究延迟装载。如果可以的话,我建议您尝试压缩照片,如果可以的话,可以降低文件大小。祝你好运!

答案 1 :(得分:1)

我通过调整现有的笔代码来调整我的需求(使用jQuery)来解决我的问题。它现在可以在IE / Firefox中再次使用

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function($) {
      $('.trigger').mouseover(function() {
       // find our span
       var elem = $(this).siblings('span');

        // get our img url
       var src = elem.attr('data-original');

        // change span to img using the value from data-original
       elem.replaceWith('<img src="' + src + '" style="display:block;position:absolute;"/>');

      });

      $('.trigger').mouseout(function() {
       // find our span
       var elem = $(this).siblings('img');

        // get our img url
       var src = elem.attr('src');

        // change span to img using the value from data-original
       elem.replaceWith('<span data-original="'+src+'"></span>');
      });
    });
</script>

<a href="/gotoo" class="trigger" target="_self" id="sid">Hover over me to fetch an image</a>
<span data-original="https://lorempixel.com/g/150/200/"></span>

答案 2 :(得分:0)

你可以放置没有src属性的图像,并将特定的src放在div或图像的href中! 然后使用jquery获取图像的一个或数据src的href,然后将其提供给图像,代码将是这样的:

     <a class="image" href="the-src-of-the-image">
         <img src="(leave this blank)">
     </a>

这是jquery

      jQuery(document).ready(function($){
         $('.image').on('hover',function(){
           var img_src = $(this).attr('href');
           $(this).children('img').attr('src',img_src);
         });
      });