gpt4 book ai didi

javascript - Laravel 5.2 中使用 javascript 的模态视图中的动态图像

转载 作者:行者123 更新时间:2023-11-28 23:20:55 24 4
gpt4 key购买 nike

我需要一些建议来动态显示图像。

我目前正在使用来自 W3Schools 示例的脚本:

http://www.w3schools.com/howto/howto_css_modal_images.asp

这是脚本:

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
@foreach($properties->files as $file) 

<div class="col-md-6 thumb">
<a class="thumbnail">
<img id="myImg" src="{{ URL::asset('uploads/products/' . $file->name) }}" alt="{{ $file->name }}" width="300" height="200">
</a>
</div>

<div id="myModal" class="modal">

<span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span>

<img class="modal-content" id="img">

<div id="caption"></div>
</div>

@endforeach

我需要在缩略图中显示动态显示的图像,因为只显示列表中的第一张图像。

在 View 中图像显示如下:

enter image description here

第一张图片以模态视图显示,但第二张图片不显示:

enter image description here

这是我在 Propertycontroller 中的显示方法:

Public function show ($ id)
     {
         $ Properties = Property :: find ($ id);
        
         $ Files = File :: where ('property_id', $ properties-> id) -> get ();
        
         Return view ('properties.show', compact ('properties', 'files'));
     }

此要求与:

Show image file by id in Laravel 5.2

如何在单击图像时在模态视图中显示图像?

最佳答案

它只显示第一张图片,因为所有图片的 id 都相同。使用 for 循环索引为 img 标签提供唯一 ID,如下所示:

@foreach($properties->files as $index=>$file) 

<div class="col-md-6 thumb">
<a class="thumbnail">
<img id="myImg<?php echo $index ?>" src="{{ URL::asset('uploads/products/' . $file->name) }}" alt="{{ $file->name }}" width="300" height="200" onclick="showImage(this,<?php echo $index ?>)">
</a>
</div>
@endforeach

showImage() 函数会将唯一的 $index 传递给您的脚本并执行此操作。

<script>
function showImage(element,i){
// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg'+i);
var modalImg = document.getElementById("img");
var captionText = document.getElementById("caption");
modal.style.display = "block";
modalImg.src = element.src;
captionText.innerHTML = element.alt;
}
</script>

同样可以设置关闭模态逻辑。希望对您有所帮助。

关于javascript - Laravel 5.2 中使用 javascript 的模态视图中的动态图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com