如何设置箱形滑块的高度

时间:2018-08-21 10:34:23

标签: javascript jquery html css

我有一个滑块(source code here),当前其高度设置为100%。但是,我希望滑块的高度为550px,这样看起来就不会太大,但是由于某种原因而无法正确地做到这一点。 以下是完整的代码和正在运行的代码段:

(function(factory){
  
  if (typeof define === 'function' && define.amd) {
      define(['jquery'], factory);
  } else if (typeof exports !== 'undefined') {
      module.exports = factory(require('jquery'));
  } else {
      factory(jQuery);
  }

})(function($){
  
  var Zippy = (function(element, settings){
    
    var instanceUid = 0;
    
    function _Zippy(element, settings){
      this.defaults = {
        slideDuration: '3000',
        speed: 500,
        arrowRight: '.arrow-right',
        arrowLeft: '.arrow-left'
      };
      
  
      this.settings = $.extend({},this,this.defaults,settings);
      
      this.initials = {
        currSlide : 0,
        $currSlide: null,
        totalSlides : false,
        csstransitions: false
      };
      
   
      $.extend(this,this.initials);
      
      this.$el = $(element);
      
      this.changeSlide = $.proxy(this.changeSlide,this);
      
      this.init();
      
      this.instanceUid = instanceUid++;
    }
    
    return _Zippy;
  
  })();
  
   Zippy.prototype.init = function(){
    
    this.csstransitionsTest();
   
    this.$el.addClass('zippy-carousel');
    this.build();
    this.events();
    this.activate();
    this.initTimer();
  };

	Zippy.prototype.csstransitionsTest = function(){
		var elem = document.createElement('modernizr');

		var props = ["transition","WebkitTransition","MozTransition","OTransition","msTransition"];

		for ( var i in props ) {
			var prop = props[i];
			var result = elem.style[prop] !== undefined ? prop : false;
			if (result){
				this.csstransitions = result;
				break;
			} 
		} 
	};
	
	Zippy.prototype.addCSSDuration = function(){
		var _ = this;
		this.$el.find('.slide').each(function(){
			this.style[_.csstransitions+'Duration'] = _.settings.speed+'ms';
		});
	}
	
	Zippy.prototype.removeCSSDuration = function(){
		var _ = this;
		this.$el.find('.slide').each(function(){
			this.style[_.csstransitions+'Duration'] = '';
		});
	}
	 
	Zippy.prototype.build = function(){
		var $indicators = this.$el.append('<ul class="indicators" >').find('.indicators');
		this.totalSlides = this.$el.find('.slide').length;
		for(var i = 0; i < this.totalSlides; i++) $indicators.append('<li data-index='+i+'>');
	};
	 
	Zippy.prototype.activate = function(){
		this.$currSlide = this.$el.find('.slide').eq(0);
		this.$el.find('.indicators li').eq(0).addClass('active');
	};

	Zippy.prototype.events = function(){
		$('body')
			.on('click',this.settings.arrowRight,{direction:'right'},this.changeSlide)
			.on('click',this.settings.arrowLeft,{direction:'left'},this.changeSlide)
			.on('click','.indicators li',this.changeSlide);
	};
	
	Zippy.prototype.clearTimer = function(){
		if (this.timer) clearInterval(this.timer);
	};
	
	Zippy.prototype.initTimer = function(){
		this.timer = setInterval(this.changeSlide, this.settings.slideDuration);
	};
	
	Zippy.prototype.startTimer = function(){
		this.initTimer();
		this.throttle = false;
	};
	
	Zippy.prototype.changeSlide = function(e){e
		if (this.throttle) return;
		this.throttle = true;
		
		this.clearTimer();
		
		var direction = this._direction(e);
		
		var animate = this._next(e,direction);
		if (!animate) return;
	
		var $nextSlide = this.$el.find('.slide').eq(this.currSlide).addClass(direction + ' active');
		
    if (!this.csstransitions){
			this._jsAnimation($nextSlide,direction);
		} else {
			this._cssAnimation($nextSlide,direction);
		}
	};
	
	Zippy.prototype._direction = function(e){
		var direction;
		
		// Default to forward movement
		if (typeof e !== 'undefined'){
			direction = (typeof e.data === 'undefined' ? 'right' : e.data.direction);
		} else {
			direction = 'right';
		}
		return direction;
	};
	
	Zippy.prototype._next = function(e,direction){
		
		var index = (typeof e !== 'undefined' ? $(e.currentTarget).data('index') : undefined);
				
		switch(true){
			
       case( typeof index !== 'undefined'):
				if (this.currSlide == index){
					this.startTimer();
					return false;
				} 
				this.currSlide = index;
			break;
			case(direction == 'right' && this.currSlide < (this.totalSlides - 1)):
				this.currSlide++;
			break;
			case(direction == 'right'):
				this.currSlide = 0;
			break;
			case(direction == 'left' && this.currSlide === 0):
				this.currSlide = (this.totalSlides - 1);
			break;
			case(direction == 'left'):
				this.currSlide--;
			break;
		}
		return true;
	};
	
	Zippy.prototype._cssAnimation = function($nextSlide,direction){
		setTimeout(function(){
			this.$el.addClass('transition');
			this.addCSSDuration();
			this.$currSlide.addClass('shift-'+direction);
		}.bind(this),100);

		setTimeout(function(){
			this.$el.removeClass('transition');
			this.removeCSSDuration();
			this.$currSlide.removeClass('active shift-left shift-right');
			this.$currSlide = $nextSlide.removeClass(direction);
			this._updateIndicators();
			this.startTimer();
		}.bind(this),100 + this.settings.speed);
	};
	
	Zippy.prototype._jsAnimation = function($nextSlide,direction){		
		var _ = this;
		
		if(direction == 'right') _.$currSlide.addClass('js-reset-left');
		
     	var animation = {};
		animation[direction] = '0%';
		
		var animationPrev = {};
		animationPrev[direction] = '100%';
		
		this.$currSlide.animate(animationPrev,this.settings.speed);
		
		$nextSlide.animate(animation,this.settings.speed,'swing',function(){
			
			_.$currSlide.removeClass('active js-reset-left').attr('style','');
			
			_.$currSlide = $nextSlide.removeClass(direction).attr('style','');
			_._updateIndicators();
			_.startTimer();
		});
	};
	
	Zippy.prototype._updateIndicators = function(){
		this.$el.find('.indicators li').removeClass('active').eq(this.currSlide).addClass('active');
	};
	
	$.fn.Zippy = function(options){
    
    return this.each(function(index,el){
      
      el.Zippy = new Zippy(el,options);
      
    });
    
  };
 
});

var args = {
	arrowRight : '.arrow-right', 
	arrowLeft : '.arrow-left', 
	speed : 1000, 
	slideDuration : 4000
};

$('.carousel').Zippy(args);
(function(factory){
  
  if (typeof define === 'function' && define.amd) {
      define(['jquery'], factory);
  } else if (typeof exports !== 'undefined') {
      module.exports = factory(require('jquery'));
  } else {
      factory(jQuery);
  }

})(function($){
  
  var Zippy = (function(element, settings){
    
    var instanceUid = 0;
    
    function _Zippy(element, settings){
      this.defaults = {
        slideDuration: '3000',
        speed: 500,
        arrowRight: '.arrow-right',
        arrowLeft: '.arrow-left'
      };
      
  
      this.settings = $.extend({},this,this.defaults,settings);
      
      this.initials = {
        currSlide : 0,
        $currSlide: null,
        totalSlides : false,
        csstransitions: false
      };
      
   
      $.extend(this,this.initials);
      
      this.$el = $(element);
      
      this.changeSlide = $.proxy(this.changeSlide,this);
      
      this.init();
      
      this.instanceUid = instanceUid++;
    }
    
    return _Zippy;
  
  })();
  
   Zippy.prototype.init = function(){
    
    this.csstransitionsTest();
   
    this.$el.addClass('zippy-carousel');
    this.build();
    this.events();
    this.activate();
    this.initTimer();
  };

	Zippy.prototype.csstransitionsTest = function(){
		var elem = document.createElement('modernizr');

		var props = ["transition","WebkitTransition","MozTransition","OTransition","msTransition"];

		for ( var i in props ) {
			var prop = props[i];
			var result = elem.style[prop] !== undefined ? prop : false;
			if (result){
				this.csstransitions = result;
				break;
			} 
		} 
	};
	
	Zippy.prototype.addCSSDuration = function(){
		var _ = this;
		this.$el.find('.slide').each(function(){
			this.style[_.csstransitions+'Duration'] = _.settings.speed+'ms';
		});
	}
	
	Zippy.prototype.removeCSSDuration = function(){
		var _ = this;
		this.$el.find('.slide').each(function(){
			this.style[_.csstransitions+'Duration'] = '';
		});
	}
	 
	Zippy.prototype.build = function(){
		var $indicators = this.$el.append('<ul class="indicators" >').find('.indicators');
		this.totalSlides = this.$el.find('.slide').length;
		for(var i = 0; i < this.totalSlides; i++) $indicators.append('<li data-index='+i+'>');
	};
	 
	Zippy.prototype.activate = function(){
		this.$currSlide = this.$el.find('.slide').eq(0);
		this.$el.find('.indicators li').eq(0).addClass('active');
	};

	Zippy.prototype.events = function(){
		$('body')
			.on('click',this.settings.arrowRight,{direction:'right'},this.changeSlide)
			.on('click',this.settings.arrowLeft,{direction:'left'},this.changeSlide)
			.on('click','.indicators li',this.changeSlide);
	};
	
	Zippy.prototype.clearTimer = function(){
		if (this.timer) clearInterval(this.timer);
	};
	
	Zippy.prototype.initTimer = function(){
		this.timer = setInterval(this.changeSlide, this.settings.slideDuration);
	};
	
	Zippy.prototype.startTimer = function(){
		this.initTimer();
		this.throttle = false;
	};
	
	Zippy.prototype.changeSlide = function(e){e
		if (this.throttle) return;
		this.throttle = true;
		
		this.clearTimer();
		
		var direction = this._direction(e);
		
		var animate = this._next(e,direction);
		if (!animate) return;
	
		var $nextSlide = this.$el.find('.slide').eq(this.currSlide).addClass(direction + ' active');
		
    if (!this.csstransitions){
			this._jsAnimation($nextSlide,direction);
		} else {
			this._cssAnimation($nextSlide,direction);
		}
	};
	
	Zippy.prototype._direction = function(e){
		var direction;
		
		// Default to forward movement
		if (typeof e !== 'undefined'){
			direction = (typeof e.data === 'undefined' ? 'right' : e.data.direction);
		} else {
			direction = 'right';
		}
		return direction;
	};
	
	Zippy.prototype._next = function(e,direction){
		
		var index = (typeof e !== 'undefined' ? $(e.currentTarget).data('index') : undefined);
				
		switch(true){
			
       case( typeof index !== 'undefined'):
				if (this.currSlide == index){
					this.startTimer();
					return false;
				} 
				this.currSlide = index;
			break;
			case(direction == 'right' && this.currSlide < (this.totalSlides - 1)):
				this.currSlide++;
			break;
			case(direction == 'right'):
				this.currSlide = 0;
			break;
			case(direction == 'left' && this.currSlide === 0):
				this.currSlide = (this.totalSlides - 1);
			break;
			case(direction == 'left'):
				this.currSlide--;
			break;
		}
		return true;
	};
	
	Zippy.prototype._cssAnimation = function($nextSlide,direction){
		setTimeout(function(){
			this.$el.addClass('transition');
			this.addCSSDuration();
			this.$currSlide.addClass('shift-'+direction);
		}.bind(this),100);

		setTimeout(function(){
			this.$el.removeClass('transition');
			this.removeCSSDuration();
			this.$currSlide.removeClass('active shift-left shift-right');
			this.$currSlide = $nextSlide.removeClass(direction);
			this._updateIndicators();
			this.startTimer();
		}.bind(this),100 + this.settings.speed);
	};
	
	Zippy.prototype._jsAnimation = function($nextSlide,direction){		
		var _ = this;
		
		if(direction == 'right') _.$currSlide.addClass('js-reset-left');
		
     	var animation = {};
		animation[direction] = '0%';
		
		var animationPrev = {};
		animationPrev[direction] = '100%';
		
		this.$currSlide.animate(animationPrev,this.settings.speed);
		
		$nextSlide.animate(animation,this.settings.speed,'swing',function(){
			
			_.$currSlide.removeClass('active js-reset-left').attr('style','');
			
			_.$currSlide = $nextSlide.removeClass(direction).attr('style','');
			_._updateIndicators();
			_.startTimer();
		});
	};
	
	Zippy.prototype._updateIndicators = function(){
		this.$el.find('.indicators li').removeClass('active').eq(this.currSlide).addClass('active');
	};
	
	$.fn.Zippy = function(options){
    
    return this.each(function(index,el){
      
      el.Zippy = new Zippy(el,options);
      
    });
    
  };
  

});

var args = {
	arrowRight : '.arrow-right', 
	arrowLeft : '.arrow-left', 
	speed : 1000, 
	slideDuration : 4000
};

$('.carousel').Zippy(args);
<div class="wrapper">
  <div class="carousel">
    <div class="inner">
      <div class="slide active">
        <div class="slide-box">
          <h1>1</h1>
          <h2>Heading 2</h2>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat.</p>
          <a href="#" class="btn btn-primary"></a>
        </div>
      </div>
      <div class="slide">
        <div class="slide-box">
          <h1>2</h1>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat.</p>
          <a href="#" class="btn btn-primary"></a>
        </div>
      </div>
      <div class="slide">
        <div class="slide-box">
          <h1>3</h1>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat.</p>
          <a href="#" class="btn btn-primary"></a>
        </div>
      </div>
    </div>
    <div class="arrow arrow-left"></div>
    <div class="arrow arrow-right"></div>
  </div>

</div>

我尝试给包装类提供500px的高度,但这似乎不是最好的方法。

在调整页面大小时,如何调整滑块的高度并将内容保留在框的中间?

Here mycodepen if needed

提前谢谢

1 个答案:

答案 0 :(得分:0)

幻灯片样式中的填充会引起高度问题:

.slide {
    text-align: center;
    padding-top: 25%;
    background-size: cover;
}

这是我对您的样式的修正,以获取正确的高度,我也将幻灯片框和文本水平和垂直居中放置:

/********For better see the text********/
p{
  color:white;
}

h2{
  color:white;
}    
/**************************************/

.wrapper{
  width:100%;
  position:relative;
  height: 50px;
}
.slide-box {
    max-width: 1300px;
    margin: 0 auto;
    padding: 54px;
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}
/**
 * Padding is set relative to the width
 * of the element, so here padding-top:60% is
 * a percentage of the width. This allows us 
 * to set the height as a ratio of the width
 *
 */
.carousel{
width: 100%;
height: 500px;
position: relative;
/* padding-top: 50%; */
overflow: hidden;
}

.inner{
    width: 100%;
    height: 100%;
    position: absolute;
    top:0;
    left: 0;
}

/**
 * ==========================
 * Animation styles
 * 
 * Notes:
 * 1. We use z-index to position active slides in-front 
 * of non-active slides
 * 2. We set right:0 and left:0 on .slide to provide us with
 * a default positioning on both sides of the slide. This allows 
 * us to trigger JS and CSS3 animations easily
 *
 */
.slide{
    width: 100%;
    height: 500px;
    position: absolute;
    top:0;
    right:0;
    left:0;
    z-index: 1;
    opacity: 0;
}

.slide.active,
.slide.left,
.slide.right{
    z-index: 2;
    opacity: 1;
}

/**
 * ==========================
 * JS animation styles
 * 
 * We use jQuery.animate to control the sliding animations
 * when CSS3 animations are not available. In order for
 * the next slide to slide in from the right, we need
 * to change the left:0 property of the slide to left:auto
 *
 */

.js-reset-left{left:auto}

/**
 * ==========================
 * CSS animation styles
 * 
 * .slide.left and .slide.right set-up
 * the to-be-animated slide so that it can slide
 * into view. For example, a slide that is about 
 * to slide in from the right will:
 * 1. Be positioned to the right of the viewport (right:-100%)
 * 2. Slide in when the style is superseded with a more specific style (right:0%)
 *
 */
.slide.left{
    left:-100%;
    right:0;
}

.slide.right{
    right:-100%;
    left: auto;
}

.transition .slide.left{left:0%}
.transition .slide.right{right:0%}

/**
 * The following classes slide the previously active
 * slide out of view before positioning behind the 
 * currently active slide
 *
 */
.transition .slide.shift-right{right: 100%;left:auto}
.transition .slide.shift-left{left: 100%;right:auto}

/**
 * This sets the CSS properties that will animate. We set the
 * transition-duration property dynamically via JS.
 * We use the browser's default transition-timing-function
 * for simplicity's sake
 * 
 * It is important to note that we are using CodePen's inbuilt
 * CSS3 property prefixer. For your own projects, you will need
 * to prefix the transition and transform properties here to ensure
 * reliable support across browsers
 *
 */
.transition .slide{
    transition-property: right, left, margin;
}

/**
 * ==========================
 * Indicators
 *
 */
.indicators{
  width:100%;
  position: absolute;
  bottom:0;
  z-index: 4;
  padding:0;
  text-align: center;
}

.indicators li{
    width: 13px;
    height: 13px;
    display: inline-block;
    margin: 5px;
    background: #fff;
    list-style-type: none;
    border-radius: 50%;
  cursor:pointer;
  transition:background 0.3s ease-out;
}

.indicators li.active{background:#93278f}

.indicators li:hover{background-color:#2b2b2b}

/**
 * ==========================
 * Arrows 
 *
 */
.arrow{
  width: 20px;
  height: 20px;
  position:absolute;
  top:50%;
  z-index:5;
  border-top:3px solid #fff;
  border-right:3px solid #fff;
  cursor:pointer;
  transition:border-color 0.3s ease-out;
}

.arrow:hover{border-color:#93278f}

.arrow-left{
  left:20px;
  transform:rotate(225deg);
}

.arrow-right{
  right:20px;
  transform:rotate(45deg);
}

/**
 * ==========================
 * For demo purposes only
 * 
 * Please note that the styles below are used
 * for the purposes of this demo only. There is no need
 * to use these in any of your own projects
 *
 */
.slide{
    text-align:left;
  background-size:cover;
  display: table-cell;
  vertical-align: middle;
}

h1{
    width:100px;
  height:100px;
  background-color:rgba(146, 45, 141,0.7);
    margin:auto;
  line-height:100px;
    color:#fff;
    font-size:2.4em;
  border-radius:50%;
  text-align: center;
}

.slide:nth-child(1){
    background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/163697/slide-1.jpg);
 }

.slide:nth-child(2){
    background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/163697/slide-2.jpg);
}

.slide:nth-child(3){
    background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/163697/slide-3.jpg);
 }