窗口调整大小后如何保持滚动位置?

时间:2015-03-03 12:38:20

标签: javascript jquery scroll google-chrome-extension scrolltop

我正在构建一个Chrome扩展程序,可以让您在网页上保存滚动位置。我遇到的问题通常是当您调整页面大小时,您正在寻找的内容可能已被推送并且不再位于相同的滚动位置。我一直在尝试构建一些可以调整滚动位置以适应调整大小的东西。我发现this solution,它更接近我正在寻找的东西,但它仍然是一些不准确的东西。它使用文档的高度和滚动位置来确定您在百分比方面的位置。然后它会在您调整页面大小时尝试保持该百分比。不幸的是,百分比并不完全准确。

我已将其集成到我的扩展程序中,我一直在尝试wikipedia article(我喜欢图纸)。我在下面添加了截图,以显示它是如何关闭的。我试图将高度增量乘以常数,但没有单个数字可行。我试图将数字四舍五入到不同的点,但同样的问题。我该怎么做才能使滚动位置更准确?

的manifest.json

{
    "name": "ScrollMark",
    "description": "Save your place on a page",
    "version": "1.1",
    "manifest_version": 2,
    "content_scripts": [{
        "js": ["jquery.min.js", "contentScript.js"],
        "matches": ["http://*/*", "https://*/*"]
  }]
}

contentScript.js

$(document).keypress(function (e) {
    if (e.which == 13) {
        console.group("User hit enter");
        console.log('window size', $(window).width(), $(window).height());
        console.log('document size', $(document).width(), $(document).outerHeight(true));           
        console.log('scroll top', $(document).scrollTop());
        console.groupEnd();
    }
});
(function () {
    var pageHeight = $(document).outerHeight(true), //get hight of element, including margin
        scrollPosition = $(document).scrollTop(),
        scrollPercent = scrollPosition / pageHeight,
        resizing = false,
        resizeTimer;
    $(window).scroll(function () {
        if (!resizing) {
            scrollPosition = $(document).scrollTop();
            scrollPercent = scrollPosition / pageHeight;
        }
    });
    $(window).resize(function () {
        resizing = true;
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
            resizing = false
        }, 500);
        pageHeight = $(document).outerHeight(true);
        $(document).scrollTop(scrollPercent * pageHeight);
    });
})();

100% View 100%查看 预计滚动位置:962 实际滚动位置:962 75% View 75%观看 预计滚动位置:1207 实际滚动位置:1211 50% View 50%观看 预计滚动位置:1534 实际滚动位置:1577 25% View 25%观看 预计滚动位置:2852 实际滚动位置:2708

2 个答案:

答案 0 :(得分:3)

为了让它完全符合你想要的方式,遗憾的是不可能,因为你无法知道响应式设计在调整大小后如何处理内容(嗯,你可以,但编写这样的代码需要数年时间) )。

但是,如果我可以给你一条建议,那就是依靠最顶层的可见元素。您可以遍历所有DOM树并找到最接近屏幕可见部分顶部的静态元素(使用偏移属性等),然后存储其完整且精确的CSS选择器。

然后,您需要做的就是恢复滚动位置:

var el = document.querySelector(storedSelector);

el && el.scrollIntoView();

这不会像你想要的那样精确,但应该没问题。

如果你仍然想要更高的精度,你可以存储除了选择器,一些偏移值,并滚动一点,但这可能是非常棘手的。

希望这会有所帮助。

答案 1 :(得分:1)

我一直在寻找同样的事情,但没有找到任何有希望的东西。我是js的初学者,但制作了一个工作剧本。它在滚动期间选择屏幕上可见的html元素,并在调整大小期间保持与所选元素相关的滚动位置。我很安静地确信我的代码并不完美,但这是我在没有丰富经验的情况下可以做到的。希望我能帮助任何人。



var html_tags = [];
	var public_closest;
	var from_top_pos;
	var public_body_height;

	
function start() {
		when_scroll();
		when_resize();
	}


function when_resize() {
	
		var count_elements = document.body.childNodes;
		var element = count_elements[public_closest];
		var closest_pos = count_elements[public_closest].offsetTop;
		var window_height = window.pageYOffset;
		
		window.scrollTo(0, closest_pos + from_top_pos);
	}




function when_scroll() {

	var window_height = document.body.scrollHeight;
	
	if (isNaN(public_body_height)) {
			public_body_height = window_height;
		}
	
	
	if (public_body_height != window_height) {
		public_body_height = window_height;
	} else {

		var how_many_elems = document.body.childNodes;
		var closest_number;
		var i;
		
		for (i = 0; i < how_many_elems.length; i++) {
				html_tags[i] = how_many_elems[i].offsetTop;
			}
				
		var closest;
		
		for (i = 0; i < html_tags.length; i++) {	
			if (isNaN(html_tags[i])) {
				} else {
					
					if (isNaN(closest)) {
							closest = html_tags[i];
						}
							
					if (Math.abs(window.pageYOffset - html_tags[i]) <= Math.abs(window.pageYOffset - closest)) {
								closest = html_tags[i];
								closest_number = i;
							}	
				}
			}
			
			if (isNaN(public_closest)) {
				} else {
					how_many_elems[public_closest].style.border = "dotted 2px #33aaff";
				}
			
		public_closest = closest_number;
		how_many_elems[closest_number].style.border = "dotted 4px #FF55AA";
				
		var count_elements = document.body.childNodes;
		var element = count_elements[public_closest];
		var current_height = count_elements[public_closest].offsetTop;
		var window_height = window.pageYOffset;
		var height_difference = window_height - current_height;
		
		from_top_pos = height_difference;

	}
}
&#13;
body>div {
		float:left;
		width:35%;
		min-width:200px;
		min-height:200px;
		max-height:1000px;
		margin:30px 10px;
		padding:20px 10px;
		font-size:22px;
		color:#33aaff;
		background-color:#ffffff;
		border:dotted 2px #33aaff;
		overflow:hidden;
	}
&#13;
<body onload="start()" onscroll="when_scroll()" onresize="when_resize()">

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at     urna. Mauris nec venenatis sapien, et auctor ex. Donec vel urna vulputate, volutpat augue non, bibendum quam. Maecenas congue id justo nec feugiat. Mauris non molestie leo. Duis non tincidunt nibh. Duis tristique dapibus sapien id commodo. In et tempor lorem.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex. Donec vel urna vulputate, volutpat augue non, bibendum quam. Maecenas congue id justo nec feugiat. Mauris non molestie leo.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex. Donec vel urna vulputate, volutpat augue non, bibendum quam.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. ullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est.Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex. Donec vel urna vulputate, volutpat augue non, bibendum quam. Maecenas congue id justo nec feugiat. Mauris non molestie leo. Duis non tincidunt nibh. Duis tristique dapibus sapien id commodo. In et tempor lorem.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex. Donec vel urna vulputate, volutpat augue non, bibendum quam. Maecenas congue id justo nec feugiat. Mauris non molestie leo.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex. Donec vel urna vulputate, volutpat augue non, bibendum quam.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna. Mauris nec venenatis sapien, et auctor ex.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio. Nullam vel massa ut nisl sollicitudin ullamcorper a at urna.</p>
</div>

<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed urna pellentesque, commodo ante ut, porttitor est. Nullam viverra dignissim sem, ac auctor dui. Phasellus ut neque odio.</p>
</div>

</body>
&#13;
&#13;
&#13;