Сообщение от Spirtikys
|
Есть ли... возможность, как с движением мыши (mouseover, mouseout)?
|
Вы можете описáть, как должны обрабатываться события
mouseover и
mouseout. Затем добавить обобщённый код, который переводит прикосновения к этим событиям.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
html {
background: black;
color: white;
}
section#images {
display: grid;
grid-template: repeat(3, 200px) / repeat(3, 200px);
}
@media(max-width: 620px) {
section#images {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: 200px;
}
}
section#images > img {
width: 100%;
height: 100%;
object-fit: cover;
filter: grayscale(1) opacity(0.5);
transition: 300ms filter;
}
section#images > img.focus {
filter: none;
}
</style>
</head>
<body>
<section id="images">
<img src="https://picsum.photos/id/237/400/400">
<img src="https://picsum.photos/id/238/400/400">
<img src="https://picsum.photos/id/239/400/400">
<img src="https://picsum.photos/id/247/400/400">
<img src="https://picsum.photos/id/248/400/400">
<img src="https://picsum.photos/id/249/400/400">
<img src="https://picsum.photos/id/257/400/400">
<img src="https://picsum.photos/id/258/400/400">
<img src="https://picsum.photos/id/259/400/400">
</section>
<button onclick="
this.textContent = document.fullscreenElement ?
'↗️ View Fullscreen' : '↙️ Exit Fullscreen';
document.fullscreenElement ?
document.exitFullscreen() :
document.documentElement.requestFullscreen();
">↗️ View Fullscreen</button>
<script>
addEventListener("mouseover", function(event) {
event.target.classList.add("focus");
});
addEventListener("mouseout", function(event) {
event.target.classList.remove("focus");
});
/* dispatch `mouseover` and `mouseout` events for touch device */
{
function dispatchMouseEventAtTarget(type, node, eventInitDict = {}) {
return dispatchEvent(Object.defineProperties(new MouseEvent(type, eventInitDict), {
target: { value: node }
}));
}
const map = new Map();
for(const type of ["start", "move", "end", "cancel"])
addEventListener("touch" + type, function(event) {
if(event instanceof TouchEvent) {
for(const touch of event.changedTouches) {
if(event.type === "touchstart") {
map.set(touch.identifier, touch.target);
dispatchMouseEventAtTarget("mouseover", event.target);
} else if(event.type === "touchmove") {
const currentTarget = map.get(touch.identifier);
const x = touch.pageX - window.pageXOffset;
const y = touch.pageY - window.pageYOffset;
const target = document.elementFromPoint(x, y);
if(currentTarget !== target) {
if(currentTarget) dispatchMouseEventAtTarget("mouseout", currentTarget);
if(target) dispatchMouseEventAtTarget("mouseover", target);
map.set(touch.identifier, target);
}
} else {
const currentTarget = map.get(touch.identifier);
if(currentTarget) setTimeout(dispatchMouseEventAtTarget, 40, "mouseout", currentTarget);
map.delete(touch.identifier);
}
}
}
});
}
</script>
</body>
</html>