Cách tạo Slider sử dụng JavaScript và CSS

Cách tạo Slider sử dụng JavaScript và CSS

Trong bài viết này, mình sẽ hướng dẫn các bạn cách tạo Slider sử dụng JavaScript và CSS thân thiện với người dùng kết hợp với chuyển động mượt mà. Đầu tiên, hãy xem kết quả những gì chúng ta sẽ làm được.

Xem trước

Image description

Cách tạo Slider sử dụng JavaScript và CSS

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>Code language: JavaScript (javascript)

Chúng ta sẽ có một div bên ngoài với lớp .img-comp-container. Nó sẽ có 2 con riêng biệt:

  • .img-comp-img: Nó sẽ chứa hình ảnh đầu tiên
  • .img-comp-overlay: Nó sẽ chứa hình ảnh thứ hai cho lớp phủ. Hình ảnh này sẽ được phủ lên trên đầu hình ảnh đầu tiên để tạo hiệu ứng slider

Mình đoán bây giờ bạn đã có một cái nhìn tổng quan về những gì mình đang làm và cách tạo Slider rồi đúng không. Bây giờ chúng ta hãy đi vào 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;
}Code language: CSS (css)

CSS này dành cho hình ảnh sẽ được hiển thị trên màn hình. Mọi thứ ở trên là tự đọc hiểu nhưng nếu bạn có bất kỳ thắc mắc nào thì hãy bình luận xuống.

.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%;
}Code language: CSS (css)

Đây là CSS cho button Slider.

JavaScript

Hiệu ứng sẽ bắt đầu từ đây. Let’s go!

Đầu tiên, chúng ta cần tìm tất cả các phần tử có lớp ‘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]);
    }Code language: JavaScript (javascript)

Tiếp theo, chúng ta sẽ tạo một hàm compareImages với một tham số 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";
}Code language: JavaScript (javascript)

Bây giờ, chúng ta sẽ tạo thanh trượt bằng cách sử dụng JavaScript trong cùng một hàm:

/*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";Code language: PHP (php)

Chúng ta sẽ thêm trình lắng nghe sự kiện. Nó sẽ được kích hoạt khi chúng ta nhấn nút chuột.

/*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);Code language: JavaScript (javascript)

Cấu trúc cơ bản của thanh trượt đã được tạo. Tiếp theo, chúng ta cần tạo một số hàm sẽ thực hiện chức năng chính của thanh trượt. Tức là trượt qua, trượt lại.

Trước tiên, chúng ta sẽ tạo hàm slideReady bên trong hàm compareImages sẽ được thực thi khi nhấn nút chuột.

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);
}Code language: JavaScript (javascript)

Tiếp theo, tạo một hàm khác bên trong hàm compareImages khi không còn nhấp vào thanh trượt nữa.

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

Bây giờ, chúng ta sẽ tạo thêm 3 hàm nữa trong compareImages mà chúng ta sẽ lấy vị trí con trỏ và di chuyển thanh trượt cho phù hợp trên cửa sổ Image.

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";
}Code language: JavaScript (javascript)

Bao đóng tất cả trong một hàm cha với tên initComparisons, thế là xong.

Dưới đây là toàn bộ code của phần JavaScript:

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";
        }
    }
}Code language: JavaScript (javascript)

Bây giờ là bước cuối cùng, sử dụng tập lệnh này trong HTML và gọi hàm initComparisons ở đầu trang mà bạn muốn có thanh trượt.

<script>
    initComparisons();
</script>Code language: HTML, XML (xml)

Sản phẩm cuối cùng sẽ trong như thế này:

Image description

Kết luận

Mình hy vọng bạn thích bài viết “Cách tạo Slider sử dụng JavaScript và CSS”. Bạn cũng có thể bookmark nó để sử dụng sau này. Thật thú vị khi tạo Slider. Nếu bạn có bất kỳ câu hỏi hoặc đề xuất nào, đừng ngần ngại comment phía dưới bài viết nhé.

Cảm ơn bạn đã theo dõi bài viết!

Các bạn có thể tham khảo các bài viết hay về CSS tại đây.


Hãy tham gia nhóm Học lập trình để thảo luận thêm về các vấn đề cùng quan tâm.

TỔNG HỢP TÀI LIỆU HỌC LẬP TRÌNH CƠ BẢN CHO NGƯỜI MỚI BẮT ĐẦU

KHOÁ HỌC BOOTCAMP JAVA/PHP/.NET TRỞ THÀNH LẬP TRÌNH VIÊN TRONG 5-6 THÁNG

Bình luận