javascript - 在 Laravel 中混合使用 PHP 和 Javascript

标签 javascript php laravel photoswipe

我在我的项目中使用 PhotoSwipe 以炫酷的渐进方式显示照片。

我想遍历排列和图像之间的关系。 我可以用 console.log() 打印出图像的数量。它有效。

1 个问题: 我想动态获取图像的数量并将它们显示在 items: HOW?

2 问题:如何动态获取照片的尺寸,例如宽度和高度?我假设可能有一些像 getOriginalHight() 这样的方法之后我想将值分配给 w:h:

function showImages() {
    let pswpElement = document.querySelectorAll('.pswp')[0];

    // build items array
    for (i = 0; i < "{{count($arrangement->images)}}"; i++) {
        console.log(i);
    }
    let items = [
        {
            src: '/storage/arrangement_images/{{$arrangement->images[1]->file_name}}',
            w: 500,
            h: 281
        },
        {
            src: 'https://placekitten.com/1200/900',
            w: 1200,
            h: 900
        }
    ];

    // define options (if needed)
    let options = {
        // optionName: 'option value'
        // for example:
        index: 0 // start at first slide
    };

    // Initializes and opens PhotoSwipe
    let gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
}

最佳答案

回答问题 1:

使用 JQuery 来做到这一点。假设您的 .php 文档中有多个图像,请使用 JQuery 的 $.each() 函数循环图像并构建 items 数组。所以它看起来像这样:

var items = [],
    $img = $('.pswp');

$img.each(function() {
  var $this = $(this),
      imageSize = [1280, 980],
      obj = {
        src: $this.attr('src'),
        w: imageSize[0],
        h: imageSize[1]
      };

  items.push(obj);
});

在这里,我使用 imageSize var 在 JS 中设置了每个图像项的宽度/高度,但您可以使用 width=""height= "" 图片的属性,如果您在模板中定义它们。

这有帮助吗?

关于javascript - 在 Laravel 中混合使用 PHP 和 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46958343/

相关文章:

javascript - 如何使用 javascript 在 html 中删除和创建新的 ul li 标签

javascript - 确定浏览器地址栏中的URL(不是真实地址)

php - 从列表中列出一类

php - laravel php pbkdf2 登录验证

mysql - "Can' t 连接到本地 MySQL 服务器”在 docker-compose 中

javascript - 渐进式 Web 应用程序 PWA 格式化视频

javascript - 使用javascript为下一个字符着色

php - 使用 PHP 的 XML RPC 连接

php - 如何在php中显示时区

html - 如何使用 LAMP 堆栈存储和访问博客内的图像?