【问题标题】:How to pass data-index attribute to the index of photoswipe js?如何将data-index属性传递给photoswipe js的索引?
【发布时间】:2016-06-11 04:23:00
【问题描述】:

关于photoswipe js:http://photoswipe.com/documentation/getting-started.html

我无法将 data-index 属性传递给 photoswipe 的索引。

HTML:

    <td>
        <div class="picture" itemscope="" itemtype="http://schema.org/ImageGallery">
            <figure style="display:initial;" itemprop="associatedMedia" itemscope="" itemtype="http://schema.org/ImageObject">
                <a class="picture" href="images/AN241_02.jpg" itemprop="contentUrl" data-size="2000x1200" data-index="0" data-title="AN241 02 55">
                    <img class="lazy thumbnail " data-original="image_cache/AN241_02-cache.jpg" itemprop="thumbnail" alt="Image description" src="image_cache/AN241_02-cache.jpg" style="display: inline;">
                </a>
            <figcaption itemprop="caption description">description</figcaption>
            </figure>
        </div>
    </td>

JS:

var onThumbnailsClick = function(e) {
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    var eTarget = e.target || e.srcElement;

    // find root element of slide
    var clickedListItem = closest(eTarget, function(el) {
        return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });

    });

    if(!clickedListItem) {
        return;
    }

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute <---HOW?

    var clickedGallery = clickedListItem.parentNode,
        childNodes = clickedListItem.parentNode.childNodes,
        numChildNodes = childNodes.length,
        nodeIndex = 0,
        index;

    for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) { 
            continue; 
        }

        if(childNodes[i] === clickedListItem) {
            index = nodeIndex;
            break;
        }
        nodeIndex++;
    }


    if(index >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( index, clickedGallery );
    }
    return false;
};

您可以在上面看到“data-index”属性位于“a”标签中,我想将其传递给 JS 中的索引。

抱歉,我对 JS 不熟悉,希望能得到任何帮助。

【问题讨论】:

    标签: javascript jquery photoswipe


    【解决方案1】:

    如果您需要获取数据索引,您必须在最后一个“If”语句之前从您点击的元素中获取此属性的值,然后将其传递给 openPhotoSwipe init 函数:)

    var newIndex = parseInt(eTarget.parentNode.getAttribute("data-index"));
    
    if(newIndex >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( newIndex, clickedGallery );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2022-10-01
      相关资源
      最近更新 更多