通过单击元素来移动滑块

问题描述 投票:0回答:1

我尝试在代码笔上使用这个滑块

https://codepen.io/MarioDesigns/pen/KvXZPK?editors=1011

$(document).ready(function() {


if ($(".comparison-slider")[0]) {
    let compSlider = $(".comparison-slider");

    //let's loop through the sliders and initialise each of them
    compSlider.each(function() {
        let compSliderWidth = $(this).width() + "px";
        $(this).find(".resize img").css({ width: compSliderWidth });
        drags($(this).find(".divider"), $(this).find(".resize"), $(this));
    });

    //if the user resizes the windows lets update our variables and resize our images
    $(window).on("resize", function() {
        let compSliderWidth = compSlider.width() + "px";
        compSlider.find(".resize img").css({ width: compSliderWidth });
    });
}
});


function drags(dragElement, resizeElement, container) {

// This creates a variable that detects if the user is using touch input insted of the mouse.
let touched = false;
window.addEventListener('touchstart', function() {
    touched = true;
});
window.addEventListener('touchend', function() {
    touched = false;
});

// clicp the image and move the slider on interaction with the mouse or the touch input
dragElement.on("mousedown touchstart", function(e) {
        
        //add classes to the emelents - good for css animations if you need it to
        dragElement.addClass("draggable");
        resizeElement.addClass("resizable");
        //create vars
        let startX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
        let dragWidth = dragElement.outerWidth();
        let posX = dragElement.offset().left + dragWidth - startX;
        let containerOffset = container.offset().left;
        let containerWidth = container.outerWidth();
        let minLeft = containerOffset + 10;
        let maxLeft = containerOffset + containerWidth - dragWidth - 10;
        
        //add event listner on the divider emelent
        dragElement.parents().on("mousemove touchmove", function(e) {
            
            // if the user is not using touch input let do preventDefault to prevent the user from slecting the images as he moves the silder arround.
            if ( touched === false ) {
                e.preventDefault();
            }
            
            let moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
            let leftValue = moveX + posX - dragWidth;

            // stop the divider from going over the limits of the container
            if (leftValue < minLeft) {
                leftValue = minLeft;
            } else if (leftValue > maxLeft) {
                leftValue = maxLeft;
            }

            let widthValue = (leftValue + dragWidth / 2 - containerOffset) * 100 / containerWidth + "%";

            $(".draggable").css("left", widthValue).on("mouseup touchend touchcancel", function() {
                $(this).removeClass("draggable");
                resizeElement.removeClass("resizable");
            });
            
            $(".resizable").css("width", widthValue);
            
        }).on("mouseup touchend touchcancel", function() {
            dragElement.removeClass("draggable");
            resizeElement.removeClass("resizable");
            
        });
    
    }).on("mouseup touchend touchcancel", function(e) {
        // stop clicping the image and move the slider
        dragElement.removeClass("draggable");
        resizeElement.removeClass("resizable");
    
    });

}

效果非常好,但我想添加一些附加功能,例如单击图像(向左或向右)并相应地移动滑块。

我对此很陌生,任何帮助将不胜感激

javascript jquery slider
1个回答
0
投票

我想我明白你想做什么。 首先,我们将在容器上添加一个新的

click
事件。

一旦发出点击,我需要计算它的位置,为此,我需要一些有关容器的信息:

  • 其相对于页面左边缘的位置 ->
    containerOffset
  • 容器的宽度(以像素为单位)(包括边框) ->
    containerWidth
  • X 轴上的点击位置(这是我们感兴趣的,因为滑块仅沿着该轴移动;我们将在 事件对象上使用 pageX 方法)->
    clickX

这给了我们(按列出的顺序)

container.on("click", function(e) {
    let containerOffset = container.offset().left;
    let containerWidth = container.outerWidth();
    let clickX = e.pageX - containerOffset;
});

现在我们有了这个,我们需要将点击位置转换为百分比来相对调整滑块,确保无论容器的宽度如何它都能正确定位。

let widthValue = (clickX * 100) / containerWidth + "%";

完成后,我们可以移动滑块:

dragElement.css("left", widthValue);
resizeElement.css("width", widthValue);

这给了我们(使用您提供的示例)

$(document).ready(function() {
    
    // If the comparison slider is present on the page lets initialise it, this is good you will include this in the main js to prevent the code from running when not needed
    if ($(".comparison-slider")[0]) {
        let compSlider = $(".comparison-slider");
    
        //let's loop through the sliders and initialise each of them
        compSlider.each(function() {
            let compSliderWidth = $(this).width() + "px";
            $(this).find(".resize img").css({ width: compSliderWidth });
            drags($(this).find(".divider"), $(this).find(".resize"), $(this));
        });

        //if the user resizes the windows lets update our variables and resize our images
        $(window).on("resize", function() {
            let compSliderWidth = compSlider.width() + "px";
            compSlider.find(".resize img").css({ width: compSliderWidth });
        });
    }
});

// This is where all the magic happens
// This is a modified version of the pen from Ege Görgülü - https://codepen.io/bamf/pen/jEpxOX - and you should check it out too.
function drags(dragElement, resizeElement, container) {
    
    // This creates a variable that detects if the user is using touch input insted of the mouse.
    let touched = false;
    window.addEventListener('touchstart', function() {
        touched = true;
    });
    window.addEventListener('touchend', function() {
        touched = false;
    });
    
     container.on("click", function(e) {
    let containerOffset = container.offset().left;
    let containerWidth = container.outerWidth();
    let clickX = e.pageX - containerOffset;
    let widthValue = (clickX * 100) / containerWidth + "%";

    dragElement.css("left", widthValue);
    resizeElement.css("width", widthValue);
  });
    
    // clicp the image and move the slider on interaction with the mouse or the touch input
    dragElement.on("mousedown touchstart", function(e) {
            
            //add classes to the emelents - good for css animations if you need it to
            dragElement.addClass("draggable");
            resizeElement.addClass("resizable");
            //create vars
            let startX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
            let dragWidth = dragElement.outerWidth();
            let posX = dragElement.offset().left + dragWidth - startX;
            let containerOffset = container.offset().left;
            let containerWidth = container.outerWidth();
            let minLeft = containerOffset + 10;
            let maxLeft = containerOffset + containerWidth - dragWidth - 10;
            
            //add event listner on the divider emelent
            dragElement.parents().on("mousemove touchmove", function(e) {
                
                // if the user is not using touch input let do preventDefault to prevent the user from slecting the images as he moves the silder arround.
                if ( touched === false ) {
                    e.preventDefault();
                }
                
                let moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
                let leftValue = moveX + posX - dragWidth;

                // stop the divider from going over the limits of the container
                if (leftValue < minLeft) {
                    leftValue = minLeft;
                } else if (leftValue > maxLeft) {
                    leftValue = maxLeft;
                }

                let widthValue = (leftValue + dragWidth / 2 - containerOffset) * 100 / containerWidth + "%";

                $(".draggable").css("left", widthValue).on("mouseup touchend touchcancel", function() {
                    $(this).removeClass("draggable");
                    resizeElement.removeClass("resizable");
                });
                
                $(".resizable").css("width", widthValue);
                
            }).on("mouseup touchend touchcancel", function() {
                dragElement.removeClass("draggable");
                resizeElement.removeClass("resizable");
                
            });
        
        }).on("mouseup touchend touchcancel", function(e) {
            // stop clicping the image and move the slider
            dragElement.removeClass("draggable");
            resizeElement.removeClass("resizable");
        
        });
    
}
$maxWidth: 960px;
$minTablet: 767px;

@mixin media($size) {
    @if $size == 'tabletUpwards' {@media screen and ( min-width : $minTablet ) { @content; }}
}

body {
    position: relative;
    background-color: #DDDDDD;
    font-family: 'helvetica', sans-serif;
    font-weight: lighter;
    font-size: 14px;
    color: #555;
    margin: 0;
    padding: 0;
    min-width: 320px;
}

h1 {
    text-transform: uppercase;
    color: #333;
}

h3 {
    font-weight: lighter;
    color: #555555;
}

a {
    position: relative;
    color: #a8244f;
    text-decoration: none;
    &:before {
        content: "";
        height: 2px;
        position: absolute;
        bottom: -5px;
        left: 0;
        right: 0;
        background-color: darken(#a8244f, 10%);
        transform: rotateY(90deg);
        transition: transform 0.2s ease-in-out;
    }
    &:hover {
        color: darken(#a8244f, 10%);
        text-decoration: none;
        &:before {
            transform: rotateY(0deg);
        }
    }
}

.split {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: strech;
    p {
        flex-basis: 100%;
        @include media('tabletUpwards') {
            flex-basis: 48%;
        }
    }
}

nav.social {
    display: inline-block;
    padding: 0;
    margin-bottom: 18px;
    li {
        list-style: none;
        float: left;
        a {
            padding: 5px;
        }
        &:first-child a {
            padding-left: 0;
        }
    }
}

.container {
    position: relative;
    width: 100%;
    margin: 50px 0;
    .inner {
        position: relative;
        width: 100%;
        max-width: $maxWidth;
        margin: 0 auto;
        overflow: hidden;
        box-sizing: border-box;
        padding: 20px 30px;
        background-color: #EEE;
    }
}

.comparison-slider-wrapper {
    position: relative;
    width: 100%;
    margin: 20px 0;
    background-color: white;

    .comparison-slider {
        position: relative;
        width: 100%;
        margin: 0;
        border: 5px white solid;
        box-sizing: border-box;
        > img {
            width: 100%;
            height: auto;
            display: block;
        }

        .overlay {
            display: none;
            position: absolute;
            width: 250px;
            bottom: 20px;
            right: 20px;
            background-color: rgba(0, 0, 0, 0.4);
            padding: 10px;
            box-sizing: border-box;
            color: #DDD;
            text-align: right;
            @include media('tabletUpwards') {
                display: block;
            }
        }

        .resize {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            width: 50%;
            overflow: hidden;
            > img {
                display: block;
            }
            .overlay {
                right: auto;
                left: 20px;
                text-align: left;
            }
        }

        .divider {
            position: absolute;
            width: 2px;
            height: 100%;
            background-color: rgba(256, 256, 256, 0.2);
            left: 50%;
            top: 0;
            bottom: 0;
            margin-left: -1px;
            cursor: ew-resize;
            &:before {
                content: "";
                position: absolute;
                width: 20px;
                height: 20px;
                left: -9px;
                top: 50%;
                margin-top: -10px;
                background-color: white;
                transform: rotate(45deg);
                transition: all 0.1s ease-in-out;
            }
            &:after {
                content: "";
                position: absolute;
                width: 12px;
                height: 12px;
                left: -5px;
                top: 50%;
                margin-top: -6px;
                background-color: white;
                transform: rotate(45deg);
                transition: all 0.1s ease-in-out;
            }
            &.draggable{
                &:before {
                    width: 30px;
                    height: 30px;
                    left: -14px;
                    margin-top: -15px;
                }
                &:after {
                    width: 20px;
                    height: 20px;
                    left: -9px;
                    margin-top: -10px;
                    background-color: #555;
                }
            }
        }
    }

    .caption {
        position: relative;
        width: 100%;
        padding: 10px;
        box-sizing: border-box;
        font-size: 12px;
        font-style: italic;
    }
}

.suppoprt-me {
    display: inline-block;
    position: fixed;
    bottom: 10px;
    left: 10px;
    width: 20vw;
    max-width: 250px;
    min-width: 200px;
    z-index: 9;
    img {
        width: 100%;
        height: auto;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="container">
 <div class="inner">
     
     <h1>Image Comparison Slider</h1>

     <h3>A cool way to show diferences between two image, using CSS3 and jQuery.</h3>
     
     <p>Checkout <a href="https://pnewton84.github.io/chindits-in-colour.html" target="_blank">this demo</a> by <a href="https://twitter.com/pnewton84" target="_blank">Pault Newton</a> on his blog.</p>
     
     <!-- COMPARISON SLIDER CODE START -->
     
     <div class="comparison-slider-wrapper">
        <!-- Comparison Slider - this div contain the slider with the individual images captions -->
        <div class="comparison-slider">
            <div class="overlay">And I am the <strong>after</strong> image.</div>
         <img src="https://raw.githubusercontent.com/Mario-Duarte/CodePen/main/assets/marioPhoto-2.jpg" alt="marioPhoto 2">
         <!-- Div containing the image layed out on top from the left -->
         <div class="resize">
             <div class="overlay">I am the <strong>before</strong> image.</div>
            <img src="https://raw.githubusercontent.com/Mario-Duarte/CodePen/main/assets/marioPhoto-1.jpg" alt="marioPhoto 1">
         </div>
         <!-- Divider where user will interact with the slider -->
         <div class="divider"></div>
        </div>
        <!-- All global captions if exist can go on the div bellow -->
        <div class="caption">I am the caption for the comparison slider and i can give in more detail a context off what you looking at, in this case we are looking at a demo of the comparison slider :)</div>
     </div>
     
     <!-- COMPARISON SLIDER CODE END -->
     
     <div class="split">
        <p>Cupcake ipsum dolor sit amet tart sesame snaps I love tart. Macaroon I love chocolate cake cupcake wafer oat cake carrot cake. Halvah lemon drops icing. Jelly beans I love lollipop danish. I love chupa chups gummi bears donut toffee. Fruitcake halvah chocolate bar chocolate. Apple pie danish liquorice sugar plum apple pie cheesecake. I love dessert caramels carrot cake cheesecake carrot cake dessert.</p>

        <p>Icing biscuit I love pudding I love. Tart tart marshmallow fruitcake cookie bear claw jujubes I love. Soufflé I love candy fruitcake pie cake gingerbread chocolate bar. Sesame snaps pudding candy. Pudding croissant candy canes gummies chocolate tart cheesecake. Gummies chupa chups candy canes tiramisu carrot cake gummi bears tart. I love toffee powder. Pie cake I love cupcake oat cake tootsie roll chocolate bar I love.</p>
     </div>
     
     <p><strong>Photography by</strong> <a href="http:mariodesigns.co.uk/" target="blank">Mario Duarte</a></p>

         <nav class="social">
             <li><strong>Follow me on: </strong></li>
             <li><a href="https://dribbble.com/MDesignsuk" target="_blank"><i class="fa fa-dribbble" aria-hidden="true"></i></a></li>
             <li><a href="https://www.behance.net/mdesignsuk" target="_blank"><i class="fa fa-behance" aria-hidden="true"></i></a></li>
             <li><a href="http://codepen.io/MarioDesigns/" target="_blank"><i class="fa fa-codepen" aria-hidden="true"></i></a></li>
             <li><a href="https://bitbucket.org/Mario_Duarte/" target="_blank"><i class="fa fa-bitbucket" aria-hidden="true"></i></a></li>
             <li><a href="https://github.com/Mario-Duarte" target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a></li>
             <li><a href="https://twitter.com/MDesignsuk" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i></a></li>
             <li><a href="https://www.instagram.com/m.duarte_/" target="_blank"><i class="fa fa-instagram" aria-hidden="true"></i></a></li>
             <li><a href="https://www.facebook.com/mariodesigns/" target="_blank"><i class="fa fa-facebook-official" aria-hidden="true"></i></a></li>
         </nav>

 </div>
</div>

<a class="suppoprt-me" href="https://www.buymeacoffee.com/marioduarte" target="_blank"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a Coffee&nbsp&emoji=&slug=marioduarte&button_colour=FF5F5F&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00"></a>

© www.soinside.com 2019 - 2024. All rights reserved.