2 回答
TA贡献1884条经验 获得超4个赞
我采取的方法是动态创建按钮并将其注入事件侦听器以放大/缩小图像。下面是我的意思的一个例子,如果您需要帮助理解其中的任何部分,请告诉我,
const scaleUp = image =>
{
const scale = parseFloat(image.getAttribute('scaler'));
image.style.transform = `scale(${scale + 0.1})`;
image.setAttribute('scaler', Math.max(0, scale + 0.1));
};
const scaleDown = image =>
{
const scale = parseFloat(image.getAttribute('scaler'));
image.style.transform = `scale(${scale - 0.1})`;
image.setAttribute('scaler', Math.max(0, scale - 0.1));
};
(async () =>
{
const images = document.querySelectorAll('img');
const buttonContainer = document.createElement('div');
buttonContainer.style.position = 'absolute';
buttonContainer.style.bottom = '15px';
buttonContainer.style.width = '100%';
buttonContainer.style.textAlign = 'center';
for (let image of images)
{
await image.decode();
const container = document.createElement('div');
container.style.position = 'relative';
container.style.display = 'inline-block';
container.style.overflow = 'hidden';
container.style.width = image.clientWidth;
container.style.height = image.clientHeight;
const containerImage = image.cloneNode();
containerImage.setAttribute('scaler', '1');
const plusButton = document.createElement('button');
const minusButton = document.createElement('button');
plusButton.textContent = '+';
minusButton.textContent = '-';
plusButton.addEventListener('click', () => scaleUp(containerImage), true);
minusButton.addEventListener('click', () => scaleDown(containerImage), true);
container.addEventListener('wheel', event =>
{
event.preventDefault();
if (event.deltaY < 0)
scaleUp(containerImage);
else if (event.deltaY > 0)
scaleDown(containerImage);
}, true);
const imageButtonContainer = buttonContainer.cloneNode();
imageButtonContainer.appendChild(minusButton);
imageButtonContainer.appendChild(plusButton);
container.appendChild(containerImage);
container.appendChild(imageButtonContainer);
image.replaceWith(container);
}
})();
<img src="https://assets.pokemon.com/assets/cms2/img/pokedex/detail/001.png" />
<img src="https://assets.pokemon.com/assets/cms2/img/pokedex/detail/002.png" />
<img src="https://assets.pokemon.com/assets/cms2/img/pokedex/detail/003.png" />
<img src="https://assets.pokemon.com/assets/cms2/img/pokedex/detail/004.png" />
<img src="https://assets.pokemon.com/assets/cms2/img/pokedex/detail/005.png" />
<img src="https://assets.pokemon.com/assets/cms2/img/pokedex/detail/006.png" />
- 2 回答
- 0 关注
- 92 浏览
添加回答
举报