使用 Js 和 CSS 创建图像滑块 预览 HTML CSS Javascript 总结

2025-06-04

使用 Js 和 CSS 创建图像滑块

预览

HTML

CSS

JavaScript

总结

在本文中,我们将创建一个界面简洁、过渡流畅的图片滑块。首先,我们来看看要构建什么。

预览

图片描述

HTML

<div class="container">
     <div class="img-comp-container">
          <div class="img-comp-img">
               <img src="a.png" height="400" width="300">
          </div>
          <div class="img-comp-img img-comp-overlay">
               <img src="b.png" height="400" width="300">
          </div>
     </div>
</div>
Enter fullscreen mode Exit fullscreen mode

我们将创建一个外部 div,其类名为.img-comp-container。它将包含两个独立的子元素。

  • .img-comp-img:它将包含第一张图片。
  • .img-comp-overlay:它将包含用于叠加的第二张图片。该图片将叠加在第一张图片之上,以产生滑动效果。

想必你现在已经大致了解了我们正在做的事情。现在我们开始讨论 CSS。

CSS

* {
    box-sizing: border-box;
}

.img-comp-container {
    position: relative;
    height: 500px;
}

.img-comp-img {
    position: absolute;
    width: auto;
    height: auto;
    overflow: hidden;
}

.img-comp-img img {
    padding: 20px;
    display: table-row;
}
.container {
    display: table;
}
Enter fullscreen mode Exit fullscreen mode

此 CSS 用于在屏幕上显示图像。
以上所有内容均不言自明,但如果您有任何疑问,请在下面评论。

.img-comp-slider {
    position: absolute;
    z-index: 9;
    cursor: ew-resize;
    /*set the appearance of the slider:*/
    width: 40px;
    height: 40px;
    background: url(slider_icon.jpg);
    background-color: #ffffff70;
    background-repeat: round;
    backdrop-filter: blur(5px);
    border-radius: 50%;
}
Enter fullscreen mode Exit fullscreen mode

此 CSS 用于滑块按钮

JavaScript

好戏就此开始。让我们从头开始。
首先,我们需要找到所有带有“overlay”(img-comp-overlay)类的元素

var x, i;
    /*find all elements with an "overlay" class:*/
    x = document.getElementsByClassName("img-comp-overlay");
    for (i = 0; i < x.length; i++) {
        /*once for each "overlay" element:
        pass the "overlay" element as a parameter when executing the compareImages function:*/
        compareImages(x[i]);
    }
Enter fullscreen mode Exit fullscreen mode

接下来我们将创建一个compareImages带有img参数的函数

function compareImages(img) {
   var slider, img, clicked = 0, w, h;
   /*get the width and height of the img element*/
   w = img.offsetWidth;
   h = img.offsetHeight;
   /*set the width of the img element to 50%:*/
   img.style.width = (w / 2) + "px";
}
Enter fullscreen mode Exit fullscreen mode

现在,我们将使用 Js 在同一个函数中创建滑块

/*create slider:*/
slider = document.createElement("DIV");
slider.setAttribute("class", "img-comp-slider");
/*insert slider*/
img.parentElement.insertBefore(slider, img);
position the slider in the middle:*/
slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
Enter fullscreen mode Exit fullscreen mode

现在,让我们添加按下鼠标按钮时触发的监听器。

/*execute a function when the mouse button is pressed:*/
slider.addEventListener("mousedown", slideReady);
/*and another function when the mouse button is released:*/
window.addEventListener("mouseup", slideFinish);    
/*or touched (for touch screens:*/
slider.addEventListener("touchstart", slideReady);
/*and released (for touch screens:*/
window.addEventListener("touchstop", slideFinish);
Enter fullscreen mode Exit fullscreen mode

现在,滑块的基本结构已经创建完毕。接下来,我们需要创建一些函数来实现滑块的主要功能,例如在图像上滑动。

为此,我们首先slideReady在函数内部创建compareImages当按下鼠标按钮时执行的函数。

function slideReady(e) {
    /*prevent any other actions that may occur when moving over the image:*/
    e.preventDefault();
    /*the slider is now clicked and ready to move:*/
    clicked = 1;
    /*execute a function when the slider is moved:*/
    window.addEventListener("mousemove", slideMove);
    window.addEventListener("touchmove", slideMove);
}
Enter fullscreen mode Exit fullscreen mode

接下来,compareImages在滑块不再被点击时,在函数内部创建另一个函数

function slideFinish() {
    /*the slider is no longer clicked:*/
    clicked = 0;
}
Enter fullscreen mode Exit fullscreen mode

现在,我们将创建另外 3 个函数,用于compareImages获取光标位置并在图像窗口中相应地移动滑块

function slideMove(e) {
    var pos;
    /*if the slider is no longer clicked, exit this function:*/
    if (clicked == 0) return false;
    /*get the cursor's x position:*/
    pos = getCursorPos(e)
        /*prevent the slider from being positioned outside the image:*/
    if (pos < 0) pos = 0;
    if (pos > w) pos = w;
    /*execute a function that will resize the overlay image according to the cursor:*/
    slide(pos);
}

function getCursorPos(e) {
    var a, x = 0;
    e = e || window.event;
    /*get the x positions of the image:*/
    a = img.getBoundingClientRect();
    /*calculate the cursor's x coordinate, relative to the image:*/
    x = e.pageX - a.left;
    /*consider any page scrolling:*/
    x = x - window.pageXOffset;
    return x;
}

function slide(x) {
    /*resize the image:*/
    img.style.width = x + "px";
    /*position the slider:*/
    slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
}
Enter fullscreen mode Exit fullscreen mode

将其全部包装在名为 name 的父函数中initComparisons
现在我们已经涵盖了所有方面,现在让我们查看完整的Scripts.js文件

function initComparisons() {
    var x, i;
    /*find all elements with an "overlay" class:*/
    x = document.getElementsByClassName("img-comp-overlay");
    for (i = 0; i < x.length; i++) {
        /*once for each "overlay" element:
        pass the "overlay" element as a parameter when executing the compareImages function:*/
        compareImages(x[i]);
    }

    function compareImages(img) {
        var slider, img, clicked = 0,
            w, h;
        /*get the width and height of the img element*/
        w = img.offsetWidth;
        h = img.offsetHeight;
        /*set the width of the img element to 50%:*/
        img.style.width = (w / 2) + "px";
        /*create slider:*/
        slider = document.createElement("DIV");
        slider.setAttribute("class", "img-comp-slider");
        /*insert slider*/
        img.parentElement.insertBefore(slider, img);
        /*position the slider in the middle:*/
        slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
        slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
        /*execute a function when the mouse button is pressed:*/
        slider.addEventListener("mousedown", slideReady);
        /*and another function when the mouse button is released:*/
        window.addEventListener("mouseup", slideFinish);
        /*or touched (for touch screens:*/
        slider.addEventListener("touchstart", slideReady);
        /*and released (for touch screens:*/
        window.addEventListener("touchstop", slideFinish);

        function slideReady(e) {
            /*prevent any other actions that may occur when moving over the image:*/
            e.preventDefault();
            /*the slider is now clicked and ready to move:*/
            clicked = 1;
            /*execute a function when the slider is moved:*/
            window.addEventListener("mousemove", slideMove);
            window.addEventListener("touchmove", slideMove);
        }

        function slideFinish() {
            /*the slider is no longer clicked:*/
            clicked = 0;
        }

        function slideMove(e) {
            var pos;
            /*if the slider is no longer clicked, exit this function:*/
            if (clicked == 0) return false;
            /*get the cursor's x position:*/
            pos = getCursorPos(e)
                /*prevent the slider from being positioned outside the image:*/
            if (pos < 0) pos = 0;
            if (pos > w) pos = w;
            /*execute a function that will resize the overlay image according to the cursor:*/
            slide(pos);
        }

        function getCursorPos(e) {
            var a, x = 0;
            e = e || window.event;
            /*get the x positions of the image:*/
            a = img.getBoundingClientRect();
            /*calculate the cursor's x coordinate, relative to the image:*/
            x = e.pageX - a.left;
            /*consider any page scrolling:*/
            x = x - window.pageXOffset;
            return x;
        }

        function slide(x) {
            /*resize the image:*/
            img.style.width = x + "px";
            /*position the slider:*/
            slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

现在最后一步,在 HTML 中使用此脚本并initComparisons在您想要滑块的页面开头调用该函数。

<script>
    initComparisons();
</script>
Enter fullscreen mode Exit fullscreen mode

最终产品将如下所示:-
图片描述

总结

希望你喜欢这篇文章,如果喜欢,别忘了点赞❤️。你也可以收藏它,方便以后使用。制作这个滑块的过程很有趣,如果你有任何疑问或建议,欢迎随时提出。再见!

文章来源:https://dev.to/anomaly3108/create-image-slider-using-js-and-css-48l3
PREV
为了避免被追踪,请在多元宇宙中浏览 发现是如何开始的 树形标签,我最喜欢的附加组件 简介:容器标签 来吧 多账户容器 最后一步:每个域的一次性临时容器 没有开销:临时容器会自动删除 结论
NEXT
React Parallax 网站设计