纯Javascript滑块

时间:2014-11-21 18:40:26

标签: javascript html css

我是Javascript的新手,我想使用JS制作简单的滑块(没有jQuery或其他插件)。

enter image description here

如您所见,我出现了一个红色框,在此下面还有另外两个框(绿色和蓝色)。我想要的是使用next和prev按钮在它们之间导航。代码应该是动态的,所以如果我添加了更多的框,它应该可以在不更新代码的情况下工作。

请检查this小提琴。

<div class="content">
         <div class="boxes">
            <div class="box-item red"></div>
            <div class="box-item blue"></div>
            <div class="box-item green"></div>
        </div>

        <a href="#" class="next">next</a>
        <a href="#" class="prev">prev</a>
     </div>

我在考虑的是: 1-计算具有类名&#34; box-item&#34;的元素数。 2-选择元素并编辑它的CSS&#34;转换&#34;平移(X,Y)&#34 ;. 3-然后将显示下一个元素。

var numItems = document.querySelectorAll('.box-item').length;

上面的JS代码计算元素的数量,我想要一些东西来帮助我通过下一个prev按钮控制盒子。有什么想法吗?

谢谢,

3 个答案:

答案 0 :(得分:1)

我建议你使用CSS3和javascript来添加删除类。

所以你有过渡和动画,你通过javasript激活它们。

以这种方式没有插件和快速幻灯片。

如果CSS3的硬件方法不能说服你,我建议你用jQuery包装它,不需要使用vanilla js来完成这样的任务。

// -------- EDIT --------------- //

我的意思是,使用vanilla javascript我猜想获取动画的方法是通过setIntervals,并增加3个内联幻灯片容器的左侧。也许是一个评论,但正如我所说的那样,并不是要经历这种痛苦,我的回答只是指出如果你有CSS3则不需要插件或库。

我注意到CSS3就是答案,这就是我提到的原因。

相关代码将

document.getElementById('myId').setAttribute("class", "firstSlide");

然后点击并

document.getElementById('myId').setAttribute("class", "secondSlide");

document.getElementById('myId').setAttribute("class", "thirdSlide");

#myId {
  transtion: all 1s ease;
}
#myId.firstSlide {
  .translateX(0) // using mixin for the sake off the example
}
#myId.secondSlide {
  .translateX(100%) // i mean the css translate, dont make me put all the prefixes
}
#myId.thirdSlide {
  .translateX(200%) 
}

当然,你可以在这之后创建一个javascript函数来计算幻灯片&gt;将移动容器的宽度设置为n * 100 +'%',并根据向前或向后移动,每次向容器translatex添加或休息100%,容器应为100%大小的容器,隐藏溢出

// ----- -----编辑//

对于自动化它你可以创建一个计算幻灯片的函数,向容器添加正确的宽度100 * slides.length,并翻译索引* 100 + 100的xtranslation,类似的东西,有很多方法可以自动化任务,这只是一个示例来说明css设置,所以基本上你声明了一般的css规则,对于一组幻灯片的细节你用js添加样式

答案 1 :(得分:1)

var helpers = {};
        helpers.once = function (fn, context) { 
            var result;
            return function() { 
                if(fn) {
                    result = fn.apply(context || this, arguments);
                    fn = null;
                }
                return result;
            };
        };
        helpers.isset = function () {
            var a = arguments, l = a.length, i = 0, undef;
            if (l === 0) {
                throw new Error('Empty isset');
            }
            while (i !== l) {
                if (a[i] === undef || a[i] === null) {
                    return false;
                }
                i++;
            }
            return true;
        };
        helpers.empty = function (mixed_var) {
            var undef, key, i, len;
            var emptyValues = [undef, null, false, 0, '', '0'];
            for (i = 0, len = emptyValues.length; i < len; i++) {
                if (mixed_var === emptyValues[i]) {
                    return true;
                }
            }
            if (typeof mixed_var === 'object') {
                for (key in mixed_var) {
                    return false;
                }   
                return true;
            }
            return false;
        };
        helpers.returnStyle = function (el, styleProp) {
            var x = undefined;
            if (this.isset(el.currentStyle)) {
                x = el.currentStyle[styleProp];
            } else if (this.isset(window.getComputedStyle)) {
                x = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
            }
            if(this.empty(x)) {
                x = '0px';
            }
            return x;
        };
        helpers.resetSliders = function (sliders) {
            for (var i = 0; i < sliders.length; i++) {
                sliders[i].resetSlider();
            }
        };
        
        // int - id to apply, 
        // loop - loop or not, 
        // sliderIntervalTime - milisecconds between loops, 
        // divsNumberShow - number of divs inside container, 
        // infiniteLoops - loop infinitely or not 
        var jsSlider = function(id, loop, sliderIntervalTime, divsNumberShow, infiniteLoops) {
            var self = this;
            this.container = undefined;
            this.containerMarginRight = 0;
            this.containerMarginLeft = 0;
            this.containerPaddingRight = 0;
            this.containerPaddingLeft = 0;
            this.containerBorderLeftWidth = 0;
            this.containerBorderRightWidth = 0;
            this.sliderInterval = undefined;
            this.tr = undefined;
            this.divs = undefined;
            this.numCallsInteval = 0;
            this.infiniteLoops = 0;
            this.loop = 0;
            this.containerWidth = 0;
            this.containerInner = 0;
            this.sliderIntervalTime = 4000;
            this.deviation = 0;
            this.divsNumberShow = 1;
            this.divsMarginRight = 0;
            this.divsMarginLeft = 0;
            this.divsPaddingRight = 0;
            this.divsPaddingLeft = 0;
            this.divsBorderLeftWidth = 0;
            this.divsBorderRightWidth = 0;
            this.pager = undefined;
            this.pagerCounter = 0;
            this.hideNext = function () {
                self.showNextPrev();
                var ctrlSelectors = self.container.getElementsByClassName("ctrl-selector");
                ctrlSelectors[1].style.display = 'none';
            };
            this.hidePrev = function () {
                self.showNextPrev();
                var ctrlSelectors = self.container.getElementsByClassName("ctrl-selector");
                ctrlSelectors[0].style.display = 'none';
            };
            this.showNextPrev = function () {
                var ctrlSelectors = self.container.getElementsByClassName("ctrl-selector");
                for (var i = 0; i < ctrlSelectors.length; i++) {
                    ctrlSelectors[i].style.display = 'block';
                }
            };
            this.showHideNextPrev = function () {
                var currentPagerLength = ((Math.ceil(self.divs.length / self.divsNumberShow)) - 1);
                if(!self.loop && (self.pagerCounter === currentPagerLength)) {
                    self.hideNext();
                } else if(!self.loop && self.pagerCounter === 0) {
                    self.hidePrev();
                } else {
                    self.showNextPrev();
                }
            };
            this.pagerReset = function () {
                var pagerElements = self.pager.getElementsByClassName("pager-element");
                for (var i = 0; i < pagerElements.length; i++) {
                    if(pagerElements[i].className === 'pager-element activated') {
                        pagerElements[i].className = 'pager-element';
                        break;
                    }
                }
                pagerElements[0].className += ' activated';
            };
            this.pagerMove = function () {
                var pagerElements = self.pager.getElementsByClassName("pager-element");
                var activatedElement = 0;
                for (var i = 0; i < pagerElements.length; i++) {
                    if(pagerElements[i].className === 'pager-element activated') {
                        pagerElements[i].className = 'pager-element';
                        activatedElement = self.pagerCounter;
                    }
                }
                var activatedCounter = activatedElement < 0 ? pagerElements.length - 1 : activatedElement % pagerElements.length;
                pagerElements[activatedCounter].className = 'pager-element activated';
            };
            this.showPagerSlide = function (counter) {
                var currentPagerLength = ((Math.ceil(self.divs.length / self.divsNumberShow)) - 1);
                self.pagerCounter = (counter < 0 ? currentPagerLength : (counter > currentPagerLength ? 0 : counter));
                self.showHideNextPrev();
                for (var i = 0; i < self.divs.length; i++) {
                    if(self.loop && self.pagerCounter === 0) {
                        self.divs[i].style.right = '0px';
                    } else if(self.loop && self.pagerCounter === (self.divs.length - 1)) {
                        self.divs[i].style.right = (currentPagerLength * (self.containerInner)) + 'px';
                    } else {
                        self.divs[i].style.right = (self.pagerCounter * self.containerInner) + 'px';
                    }
                }
                self.pagerMove();
            };
            this.showPagerSlideStopInterval = function (counter) {
                self.showPagerSlide(counter);
                self.stopSlider();
            };
            this.showNextSlide = function () {
                self.pagerCounter++;
                self.showPagerSlide(self.pagerCounter);
            };
            this.showNextSlideStopInterval = function () {
                self.showNextSlide();
                self.stopSlider();
            };
            this.showPrevSlide = function () {
                self.pagerCounter--;
                self.showPagerSlide(self.pagerCounter);
            };
            this.showPrevSlideStopInterval = function () {
                self.showPrevSlide();
                self.stopSlider();
            };
            this.stopSlider = helpers.once(function() {
                clearInterval(self.sliderInterval);
            });
            this.startSlider = function () {
                if(self.numCallsInteval > 0) {
                    self.showNextSlide();
                }
                else {
                    self.stopSlider();
                }
                if(!self.infiniteLoops) {
                    self.numCallsInteval--;
                }
            };
            this.resetSlider = function () {
                if(self.loop) {
                    self.stopSlider();
                } else {
                    self.hidePrev();
                }
                self.recalcConainer();
                self.recalcDeviation();
                for (var i = 0; i < self.divs.length; i++) {
                    self.divs[i].style.width = ((self.containerInner - self.deviation) / self.divsNumberShow) + 'px';
                    self.divs[i].style.right =  '0px';
                }
                self.pagerReset();
            };
            this.recalcConainer = function () {
                self.containerMarginRight = helpers.returnStyle(self.container, 'margin-right');
                self.containerMarginLeft = helpers.returnStyle(self.container, 'margin-left');
                self.containerPaddingRight = helpers.returnStyle(self.container, 'padding-right');
                self.containerPaddingLeft = helpers.returnStyle(self.container, 'padding-left');
                self.containerBorderLeftWidth = helpers.returnStyle(self.container, 'border-left-width');
                self.containerBorderRightWidth = helpers.returnStyle(self.container, 'border-right-width');
                self.containerWidth = self.container.offsetWidth;
                
                self.containerInner = 
                    self.containerWidth 
                    - parseInt(self.containerPaddingRight) 
                    - parseInt(self.containerPaddingLeft) 
                    - parseInt(self.containerBorderLeftWidth) 
                    - parseInt(self.containerBorderRightWidth);
            };
            this.recalcDeviation = function () {
                self.deviation = 
                    (parseInt(self.divsMarginRight)
                    + parseInt(self.divsMarginLeft)
                    + parseInt(self.divsPaddingRight)
                    + parseInt(self.divsPaddingLeft)
                    + parseInt(self.divsBorderLeftWidth)
                    + parseInt(self.divsBorderRightWidth)) * self.divsNumberShow;
            };
            this.createSlider = function (id, loop, sliderIntervalTime, divsNumberShow, infiniteLoops) {
                if(helpers.isset(id)) {
                    self.loop = helpers.isset(loop) ? loop : 1;  
                    self.sliderIntervalTime = helpers.isset(sliderIntervalTime) ? sliderIntervalTime : 4000;
                    self.divsNumberShow = helpers.isset(divsNumberShow) ? divsNumberShow : 1;
                    self.container = document.getElementById(id);
                    var ctrlSelectorNext = document.createElement('span');
                    ctrlSelectorNext.id = 'next';
                    ctrlSelectorNext.className = 'ctrl-selector';
                    ctrlSelectorNext.innerHTML = '&nbsp;';
                    ctrlSelectorNext.onclick = self.showNextSlideStopInterval;
                    self.container.appendChild(ctrlSelectorNext);
                    var ctrlSelectorPrev = document.createElement('span');
                    ctrlSelectorPrev.id = 'prev';
                    ctrlSelectorPrev.className = 'ctrl-selector';
                    ctrlSelectorPrev.innerHTML = '&nbsp;';
                    ctrlSelectorPrev.onclick = self.showPrevSlideStopInterval;
                    self.container.insertBefore(ctrlSelectorPrev ,self.container.firstChild);
                    self.pager = document.createElement('div');
                    self.pager.className = 'pager';
                    self.container.appendChild(self.pager);
                    self.divs = self.container.getElementsByClassName("element");
                    self.divsMarginRight = helpers.returnStyle(self.divs[0], 'margin-right');
                    self.divsMarginLeft = helpers.returnStyle(self.divs[0], 'margin-left');
                    self.divsPaddingRight = helpers.returnStyle(self.divs[0], 'padding-right');
                    self.divsPaddingLeft = helpers.returnStyle(self.divs[0], 'padding-left');
                    self.divsBorderLeftWidth = helpers.returnStyle(self.divs[0], 'border-left-width');
                    self.divsBorderRightWidth = helpers.returnStyle(self.divs[0], 'border-right-width');
                    self.infiniteLoops = helpers.isset(infiniteLoops) ? infiniteLoops : 0;
                    self.recalcConainer();
                    self.recalcDeviation();
                    for (var i = 0; i < self.divs.length; i++) {
                        self.divs[i].style.width = ((self.containerInner - self.deviation) / self.divsNumberShow) + 'px';
                    }
                    for (var i = 0; i < Math.ceil(self.divs.length / self.divsNumberShow); i++) {
                        var pagerElement = document.createElement('span');
                        pagerElement.className = 'pager-element';
                        pagerElement.innerHTML = i + 1;
                        if (typeof window.addEventListener === 'function'){
                            (function (_i) {
                                pagerElement.addEventListener('click', function(){
                                    self.showPagerSlideStopInterval(_i);
                                });
                            })(i);
                        }
                        self.pager.appendChild(pagerElement);
                    }
                    self.numCallsInteval = Math.ceil(self.divs.length / self.divsNumberShow) - 1;
                    if(self.loop) {
                        self.sliderInterval = setInterval(function() {
                            self.startSlider();
                        }, self.sliderIntervalTime);
                    } else {
                        self.hidePrev();
                    }
                    self.pagerReset();
                }
            };
            this.createSlider(id, loop, sliderIntervalTime, divsNumberShow, infiniteLoops);
        };
        
        var sliders = [];
        var resizing;
        
        document.addEventListener( 'DOMContentLoaded', function () {
            sliders.push(new jsSlider("sa1", 1, 4000, 1, 0));
            sliders.push(new jsSlider("sa2", 1, 4000, 2, 1));
            sliders.push(new jsSlider("sa3", 1, 4000, 3, 0));
            sliders.push(new jsSlider("sm1", 0, 4000, 1));
            sliders.push(new jsSlider("sm2", 0, 4000, 2));
            sliders.push(new jsSlider("sm3", 0, 4000, 3));
        }, false );
        
        window.addEventListener('resize', function () {
            clearTimeout(resizing);
            resizing = setTimeout(function () {
                helpers.resetSliders(sliders);}, 100);
        }, false );
img {
	vertical-align: middle;
	text-align: center
}
.quantum-slider {
	border:solid #aaa;
	border-width:1px;
	border-radius:5px; 
	width:auto; 
	margin:14px 10px; 
	color:#555; 
	font-size:1em; 
	display: block;
	overflow: hidden;
	position: relative;
	white-space: nowrap;
	padding: 24px 10px;
}
.quantum-slider .element {
	position:relative;
	display: inline-block;
	-webkit-transition:all 0.5s ease-in-out;
	-moz-transition:all 0.5s ease-in-out;
	-o-transition:all 0.5s ease-in-out;
	-ms-transition:all 0.5s ease-in-out;
	transition:all 0.5s ease-in-out 0s;
	margin: 0 24px;
	padding: 0 5px;
	right:0;
	width: auto;
	white-space: normal;
	text-align: center;
	vertical-align: middle;
}
.quantum-slider .lena {
	border: 1px solid #aaa; 
	padding: 10px 0;
}
.quantum-slider span {
	cursor:pointer;
	height:100%;
	position:absolute;
	width:24px;
	margin: 0;
	padding: 0;
	background-color:#eee;
}
.quantum-slider span:hover {
	background-color:#ddd;
}
.quantum-slider span:active {
	background-color:#ccc;
}
.quantum-slider span#prev {
	background-image:url("http://www.ciaomondo.it/code/quanton-pure-js-slider/arrow-left.png");
	background-position:50% 50%;
	background-repeat:no-repeat;
	background-size:24px auto;
	left:0;
	top:0;
	z-index:101;
}
.quantum-slider span#next {
	background-image:url("http://www.ciaomondo.it/code/quanton-pure-js-slider/arrow-right.png");
	background-position:50% 50%;
	background-repeat:no-repeat;
	background-size:24px auto;
	right:0;
	top:0;
	z-index:101;
}

.pager {
	position: relative;
	width: 100%;
	display: block;
	height: auto;
	text-align: center;
	margin: 10px 0 -10px 0;
	padding: 0;
}

.pager span {
	width: 1em;
	position: relative;
	display: inline-block;
	text-align: center;
	margin: 0 1em;
	padding: 0.2em;
	border-radius: 25%;
}

.pager span.activated{
	background-color:#ddd;
	cursor:default;
}
<h1>Javascript pure div slider (No jQuery)</h1>
<p>
	You can apply every style you want to the slider container and the slider can contain only divs.<br> 
	You must apply to all the element divs inside the slider the same style for the slider to work correctly.<br>
	The elements divs inside the slider will adapt based on the style you apply.<br> 
	If something visual is wrong with the slider when you put it inside the html pages written by you, verify if there are conflicts between the slider styles and your styles.
</p>
<h2>Slider with auto scrolling</h2>
<h3>Slider with only 1 visible div, scrolls till last div</h3>
<div id="sa1" class="quantum-slider"><!-- 
	--><div class="element">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ornare lacinia ligula vel vehicula. Phasellus.</div><!--
	--><div class="element">2. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--                                                         
	--><div class="element">3. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor suscipit enim, eu bibendum leo. Praesent sit amet lectus vitae dolor ornare dictum. Pellentesque accumsan, urna in facilisis tincidunt, felis diam euismod augue, ac mollis tortor nibh quis diam. Duis semper tincidunt aliquam. Nam malesuada.</div><!--
	--><div class="element">4. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor suscipit enim, eu bibendum leo. Praesent sit amet lectus vitae dolor ornare dictum. Pellentesque accumsan, urna in facilisis tincidunt, felis diam euismod augue, ac mollis tortor nibh quis diam. Duis semper tincidunt aliquam. Nam malesuada.</div><!--
	--><div class="element">5. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">6. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--
--></div>
<h3>Slider with 2 visible divs, scrolls infinitely</h3>
<div id="sa2" class="quantum-slider"><!-- 
	--><div class="element lena">1. <img src="http://www.ciaomondo.it/code/quanton-pure-js-slider/adele.jpg" width="150" height="150"/></div><!--
	--><div class="element lena">2. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--                                                         
	--><div class="element lena">3. <img src="http://www.ciaomondo.it/code/quanton-pure-js-slider/adele.jpg" width="150" height="150"/></div><!--
	--><div class="element lena">4. <img src="http://www.ciaomondo.it/code/quanton-pure-js-slider/adele.jpg" width="150" height="150"/></div><!--
	--><div class="element lena">5. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
--></div>
<h3>Slider with 3 visible divs, scrolls till last div</h3>
<div id="sa3" class="quantum-slider"><!-- 
	--><div class="element">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ornare lacinia ligula vel vehicula. Phasellus.</div><!--
	--><div class="element">2. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--                                                         
	--><div class="element">3. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">4. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor suscipit enim, eu bibendum leo. Praesent sit amet lectus vitae dolor ornare dictum. Pellentesque accumsan, urna in facilisis tincidunt, felis diam euismod augue, ac mollis tortor nibh quis diam. Duis semper tincidunt aliquam. Nam malesuada.</div><!--
	--><div class="element">5. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">6. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--
	--><div class="element">7. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
--></div>
<h2>Slider with manual scrolling</h2>
<h3>Slider with only 1 visible div</h3>
<div id="sm1" class="quantum-slider"><!-- 
	--><div class="element">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ornare lacinia ligula vel vehicula. Phasellus.</div><!--
	--><div class="element">2. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--                                                         
	--><div class="element">3. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">4. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor suscipit enim, eu bibendum leo. Praesent sit amet lectus vitae dolor ornare dictum. Pellentesque accumsan, urna in facilisis tincidunt, felis diam euismod augue, ac mollis tortor nibh quis diam. Duis semper tincidunt aliquam. Nam malesuada.</div><!--
	--><div class="element">5. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">6. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--
--></div>
<h3>Slider with 2 visible divs</h3>
<div id="sm2" class="quantum-slider"><!-- 
	--><div class="element">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ornare lacinia ligula vel vehicula. Phasellus.</div><!--
	--><div class="element">2. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--                                                         
	--><div class="element">3. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">4. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor suscipit enim, eu bibendum leo. Praesent sit amet lectus vitae dolor ornare dictum. Pellentesque accumsan, urna in facilisis tincidunt, felis diam euismod augue, ac mollis tortor nibh quis diam. Duis semper tincidunt aliquam. Nam malesuada.</div><!--
	--><div class="element">5. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
--></div>
<h3>Slider with 3 visible div</h3>
<div id="sm3" class="quantum-slider"><!-- 
	--><div class="element">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ornare lacinia ligula vel vehicula. Phasellus.</div><!--
	--><div class="element">2. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--                                                         
	--><div class="element">3. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">4. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor suscipit enim, eu bibendum leo. Praesent sit amet lectus vitae dolor ornare dictum. Pellentesque accumsan, urna in facilisis tincidunt, felis diam euismod augue, ac mollis tortor nibh quis diam. Duis semper tincidunt aliquam. Nam malesuada.</div><!--
	--><div class="element">5. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis id velit sed accumsan. Mauris sodales eros nec justo semper sagittis. Praesent nisl mauris, lacinia ac laoreet quis, posuere sed enim. Vestibulum quis congue nisl.</div><!--
	--><div class="element">6. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--
	--><div class="element">7. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel blandit nisi. Sed id magna mattis dolor convallis vulputate. Aenean justo leo, laoreet id est.</div><!--
--></div>

在这里你可以找到一个非常可定制的纯javascript div滑块。

https://github.com/quanton81/quanton-pure-js-slider

该脚本有很多选项。

  1. 适用于div。
  2. 它可以与你想要的所有div一起使用。
  3. 可以设置n - div的初始可见性,其他可滚动。
  4. div可以自动或手动滚动。
  5. div可以滚动到最后一个div,然后停止或无限滚动。
  6. 同一页面上可以有多个滑块,每个滑块有组合选项

答案 2 :(得分:0)

我会针对这个问题使用面向对象的方法。您可以使用相关的函数和属性创建一个滑块对象...

HTML元素具有属性(例如:class,id,value,style ..)。为此,我使用了一个名为translateVal的自定义属性来表示框的元素。该属性会跟踪元素的css translate()的当前x值。

Slider = {
	current : 0,
	boxes : document.getElementsByClassName("box-item"),
	boxWidth: 0,
	init : function(boxWidth){
		Slider.boxWidth = boxWidth;
		Slider.boxes[0].style.transform = "translate(0px, 0)";
		Slider.boxes[0].translateVal = 0;
		for (var i=1; i<Slider.boxes.length; i++) {
			Slider.boxes[i].style.transform = "translate("+(boxWidth)+"px, 0)";
			Slider.boxes[i].translateVal = boxWidth;
		}
	},
	move : function(direction){
		if (direction == "left" && Slider.current > 0){
			Slider.current--;
		} else if (direction == "right" && Slider.current < Slider.boxes.length-1){
			Slider.current++;
		}
		for (var i=0; i<Slider.boxes.length; i++) {
			var translateVal = Slider.boxWidth;
			if (i == Slider.current){
				translateVal = 0;
			} 
			Slider.boxes[i].style.transform = "translate("+(translateVal)+"px, 0)";
			Slider.boxes[i].translateVal = translateVal;
		}   
	}
}
		  
window.onload = function(){Slider.init(350)};
.content {
  width: 700px;
  height: 500px;
  margin: 120px auto 0 auto;
}
.content .boxes {
  width: 350px;
  height: 150px;
  background: #666666;
  position: relative;
  margin: 0 auto;
  overflow: hidden;
}
.content .boxes .box-item {
  position: absolute;
  width: 350px;
  height: 150px;
  right: 0;
  bottom: 0;
  left: 0;
  top: 0;
}
.content .boxes .red {
  background: red;
}
.content .boxes .blue {
  background: blue;
}
.content .boxes .green {
  background: green;
}
.content .next {
  float: right;
}
.content .prev {
  float: left;
}
<body>
<div class="content">
	<div class="boxes">
		<div class="box-item red" translateVal=""></div>
		<div class="box-item blue" translateVal=""></div>
		<div class="box-item green" translateVal=""></div>
	</div>
	<a href="#" class="next" onclick="Slider.move('right')">next</a>
	<a href="#" class="prev" onclick="Slider.move('left')">prev</a>
 </div>
 </body>