dsomm80482 2017-02-04 22:12
浏览 17
已采纳

仅在显示模态时才以模态下载图片

Okay, so I want to have a LOT of buttons on a page, which each open a different modal, populated with a gif with php. As you may have guesse, downloading a lot of quite big gifs takes a ton of time. Solution: load the gifs only when the modal containing them is actually displayed. I was advised to use the following jQuery snippet:

echo '<script>' . "
";
echo '$("#btn_'.$id.'").click(function(){' . "
";
echo '$("#img_'.$id.'").attr("src", "'.$id.".gif" . '"); });';
echo '</script>' . "
" . "
";

More readable clean, PHP-free version:

<script>
$("#btn_id").click(function(){
$("#img_id").attr("src", "id.gif"); });
</script>

The id is replaced with an actual id in php of course.

Now this snippet doesn't actually PULL the gif from the server, so in the end nothing gets displayed at all...

edit: more code

<button id="img_id" class="modalbutton" style="background-image: url(thumbs/id.gif); cursor:pointer;" onclick="document.getElementById('modal_id').style.display='block'"></button>
<div id="modal_id" class="w3-modal w3-animate-zoom" onclick="this.style.display = 'none'">
<span id="span_id" class="w3-closebtn w3-hover-red w3-container w3-padding-16 w3-display-topright">&times;</span>
<div class="modal-content" onclick="this.style.display='none'"><img id="img_id" src=""></div>
</div>
<script>
$("#btn_id").click(function(){
$("#img_id").attr("src", "id.gif"); });</script>

Demo

  • 写回答

1条回答 默认 最新

  • douqu2481 2017-02-08 21:06
    关注
    $(document).ready(function() {
        $("button").click(function(event){
            var $id = event.target.id;
            document.getElementById('modal_'+$id).style.display='block';
            var $image = $('#img_'+$id);
            var $downloadingImage = $('#imagehelper_'+$id);
            $downloadingImage.attr('src', $id+'.gif');
            $downloadingImage.on('load', function() {
                $image.attr('src', $id+'.gif');
            }).each(function() {
                if(this.complete) $(this).load();
            });
        });
    });
    

    The script gets the id of the calling element, so I don't need a lot of different snippets.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?