Integration Virtualscroll.js

Integration Virtualscroll.js

本文关键字:js Virtualscroll Integration      更新时间:2023-12-27

首先我很抱歉我是javascript的新手:p我正在尝试集成我在这里找到的virtualscroll.js在我的网页上暂时没有问题,但是。。。我找不到将此脚本集成到我的所有页面和我的主页部分占据了浏览器的100%:/此外,我也找不到如何保持我的菜单有滚动间谍(当我在页面上滚动时,菜单的下划线会自动移动)我看到了我想要的效果的例子,比如:http://www.studiofatale.com主页总是在浏览器的100%中:/我知道我不能在100%的浏览器中获得我的所有部分,但是我只需要像那样的主页

所以这是我的网站代码:

// JavaScript Document
/*
 * jQuery One Page Nav Plugin
 * http://github.com/davist11/jQuery-One-Page-Nav
 *
 * Copyright (c) 2010 Trevor Davis (http://trevordavis.net)
 * Dual licensed under the MIT and GPL licenses.
 * Uses the same license as jQuery, see:
 * http://jquery.org/license
 *
 * @version 3.0.0
 *
 * Example usage:
 * $('#nav').onePageNav({
 *   currentClass: 'current',
 *   changeHash: false,
 *   scrollSpeed: 750
 * });
 */
;(function($, window, document, undefined){
	// our plugin constructor
	var OnePageNav = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
		this.metadata = this.$elem.data('plugin-options');
		this.$win = $(window);
		this.sections = {};
		this.didScroll = false;
		this.$doc = $(document);
		this.docHeight = this.$doc.height();
	};
	// the plugin prototype
	OnePageNav.prototype = {
		defaults: {
			navItems: 'a',
			currentClass: 'current',
			changeHash: false,
			easing: 'swing',
			filter: '',
			scrollSpeed: 750,
			scrollThreshold: 0.5,
			begin: false,
			end: false,
			scrollChange: false
		},
		init: function() {
			// Introduce defaults that can be extended either
			// globally or using an object literal.
			this.config = $.extend({}, this.defaults, this.options, this.metadata);
			this.$nav = this.$elem.find(this.config.navItems);
			//Filter any links out of the nav
			if(this.config.filter !== '') {
				this.$nav = this.$nav.filter(this.config.filter);
			}
			//Handle clicks on the nav
			this.$nav.on('click.onePageNav', $.proxy(this.handleClick, this));
			//Get the section positions
			this.getPositions();
			//Handle scroll changes
			this.bindInterval();
			//Update the positions on resize too
			this.$win.on('resize.onePageNav', $.proxy(this.getPositions, this));
			return this;
		},
		adjustNav: function(self, $parent) {
			self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
			$parent.addClass(self.config.currentClass);
		},
		bindInterval: function() {
			var self = this;
			var docHeight;
			self.$win.on('scroll.onePageNav', function() {
				self.didScroll = true;
			});
			self.t = setInterval(function() {
				docHeight = self.$doc.height();
				//If it was scrolled
				if(self.didScroll) {
					self.didScroll = false;
					self.scrollChange();
				}
				//If the document height changes
				if(docHeight !== self.docHeight) {
					self.docHeight = docHeight;
					self.getPositions();
				}
			}, 250);
		},
		getHash: function($link) {
			return $link.attr('href').split('#')[1];
		},
		getPositions: function() {
			var self = this;
			var linkHref;
			var topPos;
			var $target;
			self.$nav.each(function() {
				linkHref = self.getHash($(this));
				$target = $('#' + linkHref);
				if($target.length) {
					topPos = $target.offset().top;
					self.sections[linkHref] = Math.round(topPos);
				}
			});
		},
		getSection: function(windowPos) {
			var returnValue = null;
			var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
			for(var section in this.sections) {
				if((this.sections[section] - windowHeight) < windowPos) {
					returnValue = section;
				}
			}
			return returnValue;
		},
		handleClick: function(e) {
			var self = this;
			var $link = $(e.currentTarget);
			var $parent = $link.parent();
			var newLoc = '#' + self.getHash($link);
			if(!$parent.hasClass(self.config.currentClass)) {
				//Start callback
				if(self.config.begin) {
					self.config.begin();
				}
				//Change the highlighted nav item
				self.adjustNav(self, $parent);
				//Removing the auto-adjust on scroll
				self.unbindInterval();
				//Scroll to the correct position
				self.scrollTo(newLoc, function() {
					//Do we need to change the hash?
					if(self.config.changeHash) {
						window.location.hash = newLoc;
					}
					//Add the auto-adjust on scroll back in
					self.bindInterval();
					//End callback
					if(self.config.end) {
						self.config.end();
					}
				});
			}
			e.preventDefault();
		},
		scrollChange: function() {
			var windowTop = this.$win.scrollTop();
			var position = this.getSection(windowTop);
			var $parent;
			//If the position is set
			if(position !== null) {
				$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
				//If it's not already the current section
				if(!$parent.hasClass(this.config.currentClass)) {
					//Change the highlighted nav item
					this.adjustNav(this, $parent);
					//If there is a scrollChange callback
					if(this.config.scrollChange) {
						this.config.scrollChange($parent);
					}
				}
			}
		},
		scrollTo: function(target, callback) {
			var offset = $(target).offset().top;
			$('html, body').animate({
				scrollTop: offset
			}, this.config.scrollSpeed, this.config.easing, callback);
		},
		unbindInterval: function() {
			clearInterval(this.t);
			this.$win.unbind('scroll.onePageNav');
		}
	};
	OnePageNav.defaults = OnePageNav.prototype.defaults;
	$.fn.onePageNav = function(options) {
		return this.each(function() {
			new OnePageNav(this, options).init();
		});
	};
})( jQuery, window , document );
html, body {
	height:100%;
}
body {
  margin: 0 0 0 0;
}
#content {
	width:100%;
	height:100%;
}
    
/*------menu------ */
.menu {
margin-top: 25%;
 position:fixed;
  width: 50%;
  right: -25%;
  -ms-transform: rotate(90deg); /* IE 9 */
  -webkit-transform: rotate(90deg); /* Chrome, Safari, Opera */
  transform: rotate(90deg);
}
.menu li {
  display: inline;
  text-align: center;
}
a {
  display: inline-block;
  width: 25%;
  padding: 20px 0 10px 0;
  margin: 0;
  text-decoration: none;
  color: #333;
}
.one.current ~ hr {
  margin-left: 0%;
}
.two.current ~ hr {
  margin-left: 25%;
}
.three.current ~ hr {
  margin-left: 50%;
}
.four.current ~ hr {
  margin-left: 75%;
}
.one:hover ~ hr {
  margin-left: 0%;
}
.two:hover ~ hr {
  margin-left: 25%;
}
.three:hover ~ hr {
  margin-left: 50%;
}
.four:hover ~ hr {
  margin-left: 75%;
}
hr {
  height: .25rem;
  width: 25%;
  margin: 0;
  background: rgba(0,0,0,1);
  border: none;
  transition: .3s ease-in-out;
}
/*------menu fin------ */
/*------section------ */
.section { 
width:100%; height:100%; text-align:center; display:table; color:#fff; font-size:60px; font-weight:800; text-shadow:1px 1px 0 rgba(0,0,0,0.5); letter-spacing:-2px; text-transform:uppercase;
}
.page {
	display:table-cell; vertical-align:middle;
}
#home {
	background:rgba(0,153,153,1) center no-repeat fixed; 
	-webkit-background-size:cover;
}
#work {
	background: rgba(0,102,153,1) center no-repeat fixed; 
	-webkit-background-size:cover;
}
#about {
	background: rgba(204,102,0,1) center no-repeat fixed; 
	-webkit-background-size:cover;
}
#contact {
	background: rgba(153,0,102,1) center no-repeat fixed; 
	-webkit-background-size:cover;
}
/*------section fin------ */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
		$(document).ready(function() {
			$('.menu li:eq(0)').addClass('current');
			$('.menu').onePageNav();
		});
		
	</script>
<body>
  <div class="pace"></div>
  <div id="content">
  <ul class="menu">
    <li class="one"><a href="#home">home</a></li><!--
 --><li class="two"><a href="#work">work</a></li><!--
 --><li class="three"><a href="#about">about</a></li><!--
 --><li class="four"><a href="#contact">contact</a></li>
    <hr />
  </ul>
<div class="section" id="home">
<div class="page">
WELCOME
</div>
</div>
<div class="section"  id="work">
<div class="page">
WORK
</div>
</div>
<div class="section" id="about">
<div class="page">
ABOUT ME
</div>
</div>
<div class="section" id="contact">
<div class="page">
CONTACT
</div>
</div>
</div>
</body>
</html>

因此,假设我已经准确地了解了您想要做什么,那么我就在这里为您提供了一个有效的解决方案:

http://jsfiddle.net/L7ze91vd/3/

这个插件似乎不适用于jsfiddle。。。但是div的滚动应该保持不变。

解决方案是将主div设置为一个固定的div,这样它在滚动时就不会移动,然后只需使用填充div滚动"顶部"的其他div,以填补主div不再是滚动区域一部分的空白。

我修改了html部分,使其看起来像这样:

<div class="section" id="home">
    <div class="page">
        WELCOME
    </div>
</div>
<div id="wrapper">
  <div class="section"  id="padding">
      <div class="page">
      </div>
  </div>
  <div class="section"  id="work">
      <div class="page">
          WORK
      </div>
  </div>
  <div class="section" id="about">
      <div class="page">
          ABOUT ME
      </div>
  </div>
  <div class="section" id="contact">
      <div class="page">
          CONTACT
      </div>
  </div>
</div>

还必须修改主div的菜单按钮:

<li class="one"><a href="#home">home</a></li>

至:

<li class="one"><a href="#padding">home</a></li>

我通过添加以下块修改了css:

#wrapper {
    height:100%;
    width:100%;
    position:absolute;
}
#home {
     position:fixed;
}
ul.menu {
    z-index:1;
}

有一个虚拟滚动js

var VirtualScroll = (function(document) {
	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 = 2;
	// 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);
        body {
            margin: 0;
            padding: 0;
            font-family: "Univers LT 45 Light";
            /* use this to avoid elastic overscroll on desktop (see below for mobile */
            overflow: hidden;
        }
        section {
            /* the scrollable section needs to be positioned absolute, 
               otherwise the margins are not taken into account when measuing height (CSS...) */
            position: absolute;
            width: 100%;
	
        }
        section div {
            width: 100%;
            height: 1000px;
            position: relative;
        }
        #box1 {
			background: rgba(0,153,204,1);
           
       
         
        }
        #box2 {
           
        }
        #box3 {
          
        }
        #box4 {
           
        }
        #box5 {
            z-index: 10;
            background-color: rgb(200, 0, 200);
			bottom: 0;
       
        }
   
<head>
    <title>Virtual scroll demo - simple</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable = no">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="../src/framework/VirtualScroll.js"></script>
</head>
<body>
 
    <section>
        <div id="box1" class="point">
        salut a toutes et à tous
        
        </div>
        <div id="box2" class="point">
        
Nulla facilisi. Cras fermentum leo ligula, vitae tristique mi rutrum ac. Vivamus vitae ante eros. Praesent auctor eu leo non dictum. Praesent venenatis ut quam ut cursus. In hac habitasse platea dictumst. Phasellus iaculis, ex eu scelerisque aliquet, ligula nulla semper metus, sit amet molestie leo libero a nisi. Ut egestas orci vel lorem placerat sollicitudin nec congue justo.
        
        </div>
        <div id="box3" class="point">
       
Nulla facilisi. Cras fermentum leo ligula, vitae tristique mi rutrum ac. Vivamus vitae ante eros. Praesent auctor eu leo non dictum. Praesent venenatis ut quam ut cursus. In hac habitasse platea dictumst. Phasellus iaculis, ex eu scelerisque aliquet, ligula nulla semper metus, sit amet molestie leo libero a nisi. Ut egestas orci vel lorem placerat sollicitudin nec congue justo.
        
        </div>
        <div id="box4" class="point">
       
In feugiat nunc at rhoncus vestibulum. Donec blandit id risus eget consectetur. Vestibulum ac felis iaculis, maximus turpis vel, hendrerit eros. Sed sagittis erat eu ante vestibulum efficitur. Proin viverra, ligula at luctus molestie, eros urna lobortis lectus, ut fringilla odio velit a sapien. Sed ultricies ultrices tellus a facilisis. Nam viverra arcu vel purus tempus tristique. Phasellus quis pellentesque arcu, at tincidunt dui. Curabitur imperdiet lorem vel rhoncus imperdiet. Curabitur lacinia purus non lectus posuere consectetur. Ut interdum varius arcu, ac aliquet mi auctor volutpat. Curabitur quam ante, vehicula a nulla quis, porta efficitur neque. Integer ut ornare nulla. Nulla consequat, dui eget luctus placerat, turpis metus ultricies magna, a pulvinar justo mauris sit amet dui. Aliquam vestibulum malesuada sem, sit amet ultrices diam hendrerit a.
Nulla facilisi. Cras fermentum leo ligula, vitae tristique mi rutrum ac. Vivamus vitae ante eros. Praesent auctor eu leo non dictum. Praesent venenatis ut quam ut cursus. In hac habitasse platea dictumst. Phasellus iaculis, ex eu scelerisque aliquet, ligula nulla semper metus, sit amet molestie leo libero a nisi. Ut egestas orci vel lorem placerat sollicitudin nec congue justo.</div>
        <div id="box5">
In feugiat nunc at rhoncus vestibulum. Donec blandit id risus eget consectetur. Vestibulum ac felis iaculis, maximus turpis vel, hendrerit eros. Sed sagittis erat eu ante vestibulum efficitur. Proin viverra, ligula at luctus molestie, eros urna lobortis lectus, ut fringilla odio velit a sapien. Sed ultricies ultrices tellus a facilisis. Nam viverra arcu vel purus tempus tristique. Phasellus quis pellentesque arcu, at tincidunt dui. Curabitur imperdiet lorem vel rhoncus imperdiet. Curabitur lacinia purus non lectus posuere consectetur. Ut interdum varius arcu, ac aliquet mi auctor volutpat. Curabitur quam ante, vehicula a nulla quis, porta efficitur neque. Integer ut ornare nulla. Nulla consequat, dui eget luctus placerat, turpis metus ultricies magna, a pulvinar justo mauris sit amet dui. Aliquam vestibulum malesuada sem, sit amet ultrices diam hendrerit a.
Nulla facilisi. Cras fermentum leo ligula, vitae tristique mi rutrum ac. Vivamus vitae ante eros. Praesent auctor eu leo non dictum. Praesent venenatis ut quam ut cursus. In hac habitasse platea dictumst. Phasellus iaculis, ex eu scelerisque aliquet, ligula nulla semper metus, sit amet molestie leo libero a nisi. Ut egestas orci vel lorem placerat sollicitudin nec congue justo.</div>
    </section>
  
    <script type="text/javascript">
        // Grab both red boxes
        var section = document.querySelector("section");
        // Check how much we can scroll. This value is the 
        // height of the scrollable element minus the height of the widow
        var sectionHeight = section.getBoundingClientRect().height - window.innerHeight;
        // Add easing to the scroll. Play with this value to find a setting that you like.
        var ease = 0.1;
        // Store current scroll position
        var targetX = 0, targetY = 0;
        var currentX = 0, currentY = 0;
        // Use this if you want to lock the elastic overscroll on mobile
        document.addEventListener('touchmove', function(e) { e.preventDefault(); });
        // Add virtual scroll listener
        VirtualScroll.on(function(e) {
            // Accumulate delta value on each scroll event
            targetY += e.deltaY;
            targetX += e.deltaX;
            // Clamp the value so it doesn't go too far up or down
            // The value needs to be between 0 and -sectionHeight
            targetY = Math.max(-sectionHeight, targetY);
            targetY = Math.min(0, targetY);
        });
        var scroll = function() {
            // Make sure this works across different browsers (use the shim or something)
            requestAnimationFrame(scroll);
            // Get closer to the target value at each frame, using ease. 
            // Other easing methods are also ok.
            currentY += (targetY - currentY) * ease;
            // Uncomment this line to scroll horizontally
            // currentX += (targetX - currentX) * ease;
            // Create the CSS transform string
            // (alternativly: use WebKitCSSMatrix, though it doesn't see any faster (http://jsperf.com/webkitcssmatrix-vs-translate3d)
            var v1 = "translateX(" + currentX + "px) translateY(" + currentY + "px)";// translateZ(0)";
            var v2 = "translateX(" + currentX + "px) translateY(" + currentY + "px)";// translateZ(0)";
            // Apply CSS style
            section.style['webkitTransform'] = v1;
            section.style['msTransform'] = v1;
            section.style.transform = v1;
        }
        // Start the rendering loop function
        scroll();
    </script>
</body>

它在编辑中不起作用,但注释中的链接是效果