首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >集成Virtualscroll.js

集成Virtualscroll.js
EN

Stack Overflow用户
提问于 2015-02-17 07:52:32
回答 2查看 1.7K关注 0票数 1

首先,我很抱歉,我是个javascript新手:p我正在尝试集成我在网页上找到的virtualscroll.js,暂时没有问题,但是……我找不到一个解决方案来将这个脚本集成到我所有的页面中,并让我的主页部分100%地使用浏览器:/而且我也找不到如何保持我的菜单具有滚动间谍(当我在页面上滚动时,菜单的下划线自动移动)我看到了我想要的效果的例子:http://www.studiofatale.com主页总是在100%的浏览器中:/我知道我不能在100%的浏览器中获得我的所有部分,但我只需要我的主页

下面是我的网站代码:

代码语言:javascript
复制
// 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 );
代码语言:javascript
复制
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------ */
代码语言:javascript
复制
<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>

EN

回答 2

Stack Overflow用户

发布于 2015-02-17 11:00:09

因此,假设我已经准确地弄清楚了你想要做什么,那么我现在就有一个有效的解决方案:

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

这个插件似乎不能在jsfiddle上工作...但是div的滚动应该保持不变。

解决方案是将home div设置为固定的div,这样滚动时它就不会移动,然后只需使用填充div将其他div滚动到它的“顶部”,以填补不再属于滚动区域的home div的空白。

我修改了html部分,使其如下所示:

代码语言:javascript
复制
<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>

还必须从以下位置修改home div的菜单按钮:

代码语言:javascript
复制
<li class="one"><a href="#home">home</a></li>

至:

代码语言:javascript
复制
<li class="one"><a href="#padding">home</a></li>

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

代码语言:javascript
复制
#wrapper {
    height:100%;
    width:100%;
    position:absolute;
}
#home {
     position:fixed;
}
ul.menu {
    z-index:1;
}
票数 1
EN

Stack Overflow用户

发布于 2015-02-18 06:33:36

这就是虚拟滚动js

代码语言:javascript
复制
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);
代码语言:javascript
复制
        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;
       
        }
代码语言:javascript
复制
<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>

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28552387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档