为什么我的脚本在ajax调用后不起作用?

时间:2016-01-05 17:16:53

标签: javascript jquery ajax

我创建了一个ajax网站,我在我的一个页面中有一个插件js我加载了ajax所以当我调用我的页面时脚本不起作用......但是!当我调整此页面的功能工作!如果我在这个页面中插入Jquery脚本完美地工作。 那么为什么我可以在我调整大小时获得它而不是在我加载页面时?

这是我的page.html:

<div class="section vs-section" data-speed="0.4">
  <div class="vs-transform back" data-speed="0.5">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform" data-speed="0.35"><a href="projet1.html"><h3 id="short-title">You inspire.</h3></a>
  </div>
  <div class="vs-transform back" data-speed="0.5">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform back" data-speed="0.4">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform" data-speed="0.35"><a href="projet2.html"><h3>Orange.</h3></a>
  </div>
  <div class="vs-transform back" data-speed="0.37">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform back" data-speed="0.38">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform" data-speed="0.35"><a href="projet3.html"><h3>Andaman.</h3></a>
  </div>
  <div class="vs-transform back" data-speed="0.38">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform back" data-speed="0.3">
    <div class="overlay"></div>
  </div>
  <div class="vs-transform back" data-speed="0.3">
    <div class="overlay"></div>
  </div>
</div>

<script src="js/main.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function() {


    var section = document.querySelector('.vs-section');
    var divs = document.querySelectorAll('.vs-transform');

    var smooth = new Smooth({
      direction: 'horizontal',
      section: section,
      ease: 0.1,
      els: divs
    });
    smooth.init();

  });
</script>

这是我的main.js:

&#13;
&#13;
   
(function () {
	alert('salut');
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
 
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
 
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

var vs = (function(document) {
	
	if("undefined" != typeof module && "undefined" != typeof module.exports) var vs = module.exports = {}; else var vs = {};
	
	var numListeners, listeners = [], initialized = false;

	var touchStartX, touchStartY;

	// [ These settings can be customized with the options() function below ]
	// Mutiply the touch action by two making the scroll a bit faster than finger movement
	var touchMult = 1;
	// Firefox on Windows needs a boost, since scrolling is very slow
	var firefoxMult = 15;
	// How many pixels to move with each key press
	var keyStep = 120;
	// General multiplier for all mousehweel including FF
	var mouseMult = 1;

	var bodyTouchAction;

	var hasWheelEvent = 'onwheel' in document;
	var hasMouseWheelEvent = 'onmousewheel' in document;
	var hasTouch = 'ontouchstart' in document;
	var hasTouchWin = navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1;
	var hasPointer = !!window.navigator.msPointerEnabled;
	var hasKeyDown = 'onkeydown' in document;

	var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;

	var event = {
		y: 0,
		x: 0,
		deltaX: 0,
		deltaY: 0,
		originalEvent: null
	};

	vs.on = function(f) {
		if(!initialized) initListeners(); 
		listeners.push(f);
		numListeners = listeners.length;
	}

	vs.options = function(opt) {
		keyStep = opt.keyStep || 120;
		firefoxMult = opt.firefoxMult || 15;
		touchMult = opt.touchMult || 2;
		mouseMult = opt.mouseMult || 1;
	}

	vs.off = function(f) {
		listeners.splice(f, 1);
		numListeners = listeners.length;
		if(numListeners <= 0) destroyListeners();
	}

	var notify = function(e) {
		event.x += event.deltaX;
		event.y += event.deltaY;
		event.originalEvent = e;

		for(var i = 0; i < numListeners; i++) {
			listeners[i](event);
		}
	}

	var onWheel = function(e) {
		// In Chrome and in Firefox (at least the new one)
		event.deltaX = e.wheelDeltaX || e.deltaX * -1;
		event.deltaY = e.wheelDeltaY || e.deltaY * -1;

		// for our purpose deltamode = 1 means user is on a wheel mouse, not touch pad 
		// real meaning: https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent#Delta_modes
		if(isFirefox && e.deltaMode == 1) {
			event.deltaX *= firefoxMult;
			event.deltaY *= firefoxMult;
		} 

		event.deltaX *= mouseMult;
		event.deltaY *= mouseMult;

		notify(e);
	}

	var onMouseWheel = function(e) {
		// In Safari, IE and in Chrome if 'wheel' isn't defined
		event.deltaX = (e.wheelDeltaX) ? e.wheelDeltaX : 0;
		event.deltaY = (e.wheelDeltaY) ? e.wheelDeltaY : e.wheelDelta;

		notify(e);	
	}

	var onTouchStart = function(e) {
		var t = (e.targetTouches) ? e.targetTouches[0] : e;
		touchStartX = t.pageX;	
		touchStartY = t.pageY;
	}

	var onTouchMove = function(e) {
		// e.preventDefault(); // < This needs to be managed externally
		var t = (e.targetTouches) ? e.targetTouches[0] : e;

		event.deltaX = (t.pageX - touchStartX) * touchMult;
		event.deltaY = (t.pageY - touchStartY) * touchMult;
		
		touchStartX = t.pageX;
		touchStartY = t.pageY;

		notify(e);
	}

	var onKeyDown = function(e) {
		// 37 left arrow, 38 up arrow, 39 right arrow, 40 down arrow
		event.deltaX = event.deltaY = 0;
		switch(e.keyCode) {
			case 37:
				event.deltaX = -keyStep;
				break;
			case 39:
				event.deltaX = keyStep;
				break;
			case 38:
				event.deltaY = keyStep;
				break;
			case 40:
				event.deltaY = -keyStep;
				break;
		}

		notify(e);
	}

	var initListeners = function() {
		if(hasWheelEvent) document.addEventListener("wheel", onWheel);
		if(hasMouseWheelEvent) document.addEventListener("mousewheel", onMouseWheel);

		if(hasTouch) {
			document.addEventListener("touchstart", onTouchStart);
			document.addEventListener("touchmove", onTouchMove);
		}
		
		if(hasPointer && hasTouchWin) {
			bodyTouchAction = document.body.style.msTouchAction;
			document.body.style.msTouchAction = "none";
			document.addEventListener("MSPointerDown", onTouchStart, true);
			document.addEventListener("MSPointerMove", onTouchMove, true);
		}

		if(hasKeyDown) document.addEventListener("keydown", onKeyDown);

		initialized = true;
	}

	var destroyListeners = function() {
		if(hasWheelEvent) document.removeEventListener("wheel", onWheel);
		if(hasMouseWheelEvent) document.removeEventListener("mousewheel", onMouseWheel);

		if(hasTouch) {
			document.removeEventListener("touchstart", onTouchStart);
			document.removeEventListener("touchmove", onTouchMove);
		}
		
		if(hasPointer && hasTouchWin) {
			document.body.style.msTouchAction = bodyTouchAction;
			document.removeEventListener("MSPointerDown", onTouchStart, true);
			document.removeEventListener("MSPointerMove", onTouchMove, true);
		}

		if(hasKeyDown) document.removeEventListener("keydown", onKeyDown);

		initialized = false;
	}

	return vs;
})(document);


var Smooth = function(opt) {

	if (!(this instanceof Smooth))
		return new Smooth(opt)
		
	this.createBound();

	opt = opt || {}

	this.rAF = undefined;
	
	this.pos = { targetX: 0, targetY: 0, currentX: 0, currentY: 0 };
	
	this.direction = opt.direction || 'vertical';
	
	this.section = opt.section || document.querySelector('.vs-section');
	
	this.ease = opt.ease || 0.1;
	
	this.els = (typeof opt.els != 'undefined') ? Array.prototype.slice.call(opt.els, 0) : [this.section];
	
	this.to = Array.prototype.slice.call(document.querySelectorAll('.vs-scrollto'), 0);

	this.bounding = (this.direction == 'vertical')
		? this.section.getBoundingClientRect().height - window.innerHeight
		: this.section.getBoundingClientRect().left + this.section.getBoundingClientRect().right - window.innerHeight
		
};

Smooth.prototype.constructor = Smooth;

Smooth.prototype.init = function(){

	var self = this;

	vs.on(this.calc);

	this.els.forEach(function(el){
		el.speed = (self.els.length >= 2) ? el.getAttribute('data-speed') : 1;
	});

	this.to.forEach(function(el){
		var data = el.getAttribute('data-scroll');
		
		el.targetPos = (!isNaN(data))
			? data
			: (self.direction == 'vertical')
				? document.querySelector('.'+data).getBoundingClientRect().top
				: document.querySelector('.'+data).getBoundingClientRect().left
		
		el.addEventListener('click', self.getTo.bind(self, el));
	});
	
	document.addEventListener('touchmove', this.prevent);
	window.addEventListener('resize', this.resize);
	
	this.run();

};

Smooth.prototype.createBound = function(){
	
	['calc', 'getTo', 'prevent', 'resize']
	.forEach(function(fn) {
		this[fn] = this[fn].bind(this);
	}, this);
    
};

Smooth.prototype.prevent = function(e){

	e.preventDefault();

};

Smooth.prototype.calc = function(e){
	
	this.pos.targetY += e.deltaY;
	this.pos.targetX += e.deltaX || e.deltaY
	
	this.pos.targetY = Math.max(this.bounding * -1, this.pos.targetY);
	this.pos.targetY = Math.min(0, this.pos.targetY);

	this.pos.targetX = Math.max(this.bounding * -1, this.pos.targetX);
	this.pos.targetX = Math.min(0, this.pos.targetX);

};

Smooth.prototype.run = function(){

	var self = this;
	var t, s, v, b, r;

	this.pos.currentY += (this.pos.targetY - this.pos.currentY) * this.ease;
	this.pos.currentX += (this.pos.targetX - this.pos.currentX) * this.ease;

	this.els.forEach(function(el) {

		t = (self.direction == 'vertical')
			? 'matrix3d(1,0,0.00,0,0.00,1,0.00,0,0,0,1,0,0,' + (self.pos.currentY * el.speed).toFixed(2) + ',0,1)'
			: 'matrix3d(1,0,0.00,0,0.00,1,0.00,0,0,0,1,0,' + (self.pos.currentX * el.speed).toFixed(2) + ',0,0,1)'
		s = el.style;

		s['webkitTransform'] = t;
		s['msTransform'] = t;
		s.transform = t;
	
	});
	
	this.rAF = requestAnimationFrame(this.run.bind(this));

};

Smooth.prototype.getTo = function(self, el){

	if(this.direction == 'vertical') this.pos.targetY = -el.target.targetPos;
	else this.pos.targetX = -el.target.targetPos;
	
};

Smooth.prototype.scrollTo = function(offset){

	if(this.direction == 'vertical') this.pos.targetY = -offset;
	else this.pos.targetX = -offset;
	
};

Smooth.prototype.resize = function(){

	this.bounding = (this.direction == 'vertical')
		? this.section.getBoundingClientRect().height - window.innerHeight
		: this.section.getBoundingClientRect().left + this.section.getBoundingClientRect().right - window.innerHeight

};

Smooth.prototype.destroy = function(){

	vs.off(this.calc);
	
	cancelAnimationFrame(this.rAF);
	this.rAF = undefined;
	
	this.to.forEach(function(el){
		el.removeEventListener('click', self.getTo);
	});
 	
	document.removeEventListener('touchmove', this.prevent);
	window.removeEventListener('resize', this.resize);

};
&#13;
&#13;
&#13;

和我的ajax:

&#13;
&#13;
$(document).ready(function(){
	
    $("#menu a").click(function(){ 
       page=$(this).attr("href");
        $.ajax({
            url: "pages/"+page,
            cache:false,
            success:function(html){
                afficher(html);
				history.pushState({key : 'value'}, 'hash', page);
            }, 
            error:function(XMLHttpRequest,textStatus, errorThrown){
                afficher("erreur lors du chagement de la page");
            }
        });
        return false;
    });
	
     $('#container').on('click', '.vs-transform a', function(){
	 var page=$(this).attr("href");
        $.ajax({
            url: "pages/"+page,
            cache:false,
            success:function(html){
               	showed(html);
				history.pushState({key : 'value'}, 'hash', page);
            },
            error:function(XMLHttpRequest,textStatus, errorThrown){
                showed("erreur lors du chagement de la page");
            }
        });
        return false;
	}); 
window.onpopstate = function(event){
		if(event.state === null){
			   // alert('yo');
		}
	};
});

		
function afficher(data){
$("#container").delay( 100 ).fadeOut(400,function(){
    $("#container").empty();				
    $("#container").append(data);
    $("#container").fadeIn(500);	
});
}

function showed(data){
$("#container").delay( 100 ).fadeOut(400,function(){
    $("#container").empty();				
    $("#container").append(data);
    $("#container").fadeIn(500);	
});
}
&#13;
&#13;
&#13;

和我的index.php,我称之为我的ajax:

&#13;
&#13;
        <div id="menu">
    	<a id="collection" class="link nav" href="index.html">
        <span>collection</span>
    	<a id="about" class="link nav" href="about.html">
        <span>About</span></a>
    </div>
    
    <div id="container">
   <?php
   $d="pages/";
   if(isset($_GET['p'])){
	   $p=strtolower($_GET['p']);
    if(preg_match("/^[a-z0-9\-]+$/",$p) && file_exists($d.$p.".html")){
       include $d.$p.".html";
    }
	 else{
	   include $d."404.html";
		}
		}
	 else{
	   include $d."index.html";
		}
   ?>
	</div>
    
    <div id="footer">
    		<div class="more-button">
      			<a href="#" class="share">Follow me</a>
        	<div class="social">
            	<a href="http://www.google.fr"><img src="img/icon/Facebook.png"></a> 
            	<a href="#"><img src="img/icon/instagram.png"></a> 
                <a href="#"><img src="img/icon/tumbler.png"></a> 
            </div>
            </div>
  
   </div> 
   
  
&#13;
&#13;
&#13;

0 个答案:

没有答案