javascript - 仅当显示模态时才下载模态中的图片

标签 javascript php jquery

好吧,所以我想在页面上有很多按钮,每个按钮都会打开一个不同的模式,并用 php 填充一个 gif。正如您可能已经猜到的那样,下载大量相当大的 gif 动图需要花费大量时间。 解决方案:仅当包含 gif 的模态实际显示时才加载 gif。建议我使用以下 jQuery 片段:

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

更易读、干净、无 PHP 的版本:

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

当然,该 id 会替换为 php 中的实际 id。

现在这个片段实际上并没有从服务器中提取 gif,所以最终什么也没有显示......

编辑:更多代码

<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

最佳答案

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

脚本获取调用元素的 id,因此我不需要很多不同的代码片段。

关于javascript - 仅当显示模态时才下载模态中的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046227/

相关文章:

javascript - 分割字符串并得到一个数字

PHP和MySQL如何查询小数列

java - 如何使用 Google Finance API 获取股票报价?

javascript - 比较动态 JSON 文件 - JavaScript

jquery - 如何禁用 jQuery.jplayer 自动播放?

javascript - d3 使用按钮缩放并双击但不要使用滚轮缩放

javascript - 无法选择之前选择的选项

javascript - 删除 div 中的 <br>,但不删除该 div 子级中的 <br>

javascript - 在 HTML 中,如果你第二次加载同一个脚本文件,它还会被加载吗?

php - 用逗号分割字符串而忽略其他逗号(未引用)