gpt4 book ai didi

Javascript 照片库——查看完整图像

转载 作者:行者123 更新时间:2023-12-02 23:13:09 24 4
gpt4 key购买 nike

我在 Flask 应用程序中构建了一个画廊。为了加载目的,网页加载缩略图。我正在尝试使用 Javascript 来允许用户单击缩略图并查看完整图像。我遇到的问题是,javascript 似乎只适用于 <div id="image_con"></div> 的第一个实例。 。如何让该函数适用于 div 的所有实例?或者说我的设置方式是否有可能?

HTML:

{% block content %}
{% for x in names %}
<div class="date_con">
<h2>{{ x }}</h2>
{% for y in names[x] %}
<div class="event_con">
<span class="event_data">{{ y['date_parsed'] }}</span>
<span class="event_data">{{ y['title'] }}</span>
</div>
<div class="image_con" id="image_con">
{% for w in y['thumbs'] %}
<img class="image_small" src="{{ url_for('static', filename='thumbnails/' + w + '')}}" alt="{{ y['id'] }}">
{% endfor %}
</div>
<div class="cover" id="{{ y['id'] }}">

{% for z in y['fulls'] %}
<img class="image_big" id="{{ z }}" style="display: none;" onclick="EventHandler(this.id)"
src="{{ url_for('static', filename='gallery/' + z + '')}}" alt="error">
{% endfor %}
</div>

{% endfor %}
</div>
{% endfor %}
{% endblock content %}

Javascript:

var hit = false,
image_small = document.getElementById('image_con'),
active = null;

image_small.onclick = function (e) {
var i = 0, tgt = e.target, items;
if (tgt === this) return;
items = children(image_small);
var id = tgt.getAttribute('alt');
console.log(id);
while (tgt.parentNode !== this) tgt = tgt.parentNode;
while (items[i] !== tgt) i++;
// activate the image
var tar = document.getElementById(id).children;
tar[i].style.display = 'block';
document.getElementById(id).style.display = 'block';
output('index : ' + i);
// helpers
document.getElementsByTagName('body')[0].style.overflow = 'hidden';
document.getElementsByClassName('cover')[0].style.display = 'flex';
};

function children(el) {
var i = 0, children = [], child;
while (child = el.childNodes[i++]) {
if (child.nodeType === 1) children.push(child);
}
return children;
};

function output(s) {
console.log(s);
};

function EventHandler(e) {
console.log('id = ' + e);
document.getElementById(e).style.display = 'none';
document.getElementsByTagName('body')[0].style.overflow = 'auto';
document.getElementsByClassName('cover')[0].style.display = 'none';
};

最佳答案

要确保每个图像都有一个监听器,请尝试向父级 image_con 添加一个监听器,而不是每个图像。

document.getElementById('image_con').addEventListener('click', event => {
const { target } = event;
if (target.classList.contains('image_small')) {
/**
* the rest of the click handler goes here
*/
}
});

关于Javascript 照片库——查看完整图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57263014/

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