How can JS achieve the effect of image sliding door?
One way to achieve the image sliding door effect is by using JavaScript and CSS.
HTML section:
<div class="container">
<div class="door">
<div class="front">
<img src="image.jpg" alt="Image">
</div>
<div class="back">
<img src="image.jpg" alt="Image">
</div>
</div>
</div>
CSS section:
.container {
width: 400px;
height: 300px;
position: relative;
margin: 0 auto;
overflow: hidden;
}
.door {
width: 50%;
height: 100%;
position: absolute;
top: 0;
transition: transform 0.5s;
}
.front {
width: 100%;
height: 100%;
overflow: hidden;
}
.back {
width: 100%;
height: 100%;
transform: translateX(-100%);
overflow: hidden;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}
JavaScript section:
const door = document.querySelector('.door');
let isOpen = false;
door.addEventListener('click', function() {
if (!isOpen) {
door.style.transform = 'translateX(100%)';
isOpen = true;
} else {
door.style.transform = 'translateX(0)';
isOpen = false;
}
});
The above code implements an image of a sliding door effect, where clicking on the image can open or close the door. The CSS section defines the style and animation for the door, while the JavaScript section toggles the door’s state by listening for click events.