好吧,所以我想在页面上有很多按钮,每个按钮都会打开一个不同的模式,并用 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">×</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>
最佳答案
$(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/