html 断点观察器 - 当页面越过CSS断点时,调用回调,传递表示您已离开的断点的对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 断点观察器 - 当页面越过CSS断点时,调用回调,传递表示您已离开的断点的对象相关的知识,希望对你有一定的参考价值。

<html>
<head>
	<title>-- == TEST == --</title>
</head>

<style>

	body {
		background: #FF1493;
	}

	@media screen and (min-width: 768px) {
		body {
			background: #228B22;
		}
	}

	@media screen and (min-width: 1024px) {
		body {
			background: #00FFFF;
		}
	}

</style>

<body>

<script>


	var breakpoints = [
		{minWidth: 0, name: 'small'},
		{minWidth: 768, name: 'medium'},
		{minWidth: 1024, name: 'large'}
	].reverse();

	// When window size crosses breakpoint, callback is called with two arguments
	// was - object - the breakpoint we've just left
	// is - object - the breakpoint we've just entered
	function breakpointWatcher(breakpoints, callback) {

		var was = getCurrentBreakpoint();
		console.log('STARTING BREAKPOINT  ' + was.name);

		window.onresize = debounce(resizeHandler, 100);

		function resizeHandler() {
			var is = getCurrentBreakpoint();
			if (is.minWidth !== was.minWidth) {
				callback(was, is);
			}			;
			was = is;
		}

		// Returns a function, that, as long as it continues to be invoked, will not
		// be triggered. The function will be called after it stops being called for
		// N milliseconds. If `immediate` is passed, trigger the function on the
		// leading edge, instead of the trailing.
		function debounce(func, wait, immediate) {
			var timeout;
			return function () {
				var context = this, args = arguments;
				clearTimeout(timeout);
				timeout = setTimeout(function () {
					timeout = null;
					if (!immediate) func.apply(context, args);
				}, wait);
				if (immediate && !timeout) func.apply(context, args);
			};
		};

		function getCurrentBreakpoint() {
			var docWidth = getDocWidth();
			for (var i = 0; i < breakpoints.length; i++) {
				if (docWidth >= breakpoints[i].minWidth) {
					return breakpoints[i];
				}
			}
		}

		function getDocWidth() {
			return Math.max(document.documentElement["clientWidth"], document.body["scrollWidth"], document.documentElement["scrollWidth"], document.body["offsetWidth"], document.documentElement["offsetWidth"]);
		}

	}

	breakpointWatcher(breakpoints, function (was, is) {
		console.log('Left ' + was.name);
		console.log('Entered ' + is.name);
	});

</script>

</body>
</html>

以上是关于html 断点观察器 - 当页面越过CSS断点时,调用回调,传递表示您已离开的断点的对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在页面刷新时保留 Chrome DOM 断点?

响应式断点触发的 CSS 过渡

pycharm断点调试

一、Charles的断点无法再跳转至断点页面解决办法

myeclipse开发jsp怎么进入断点调试

当反向顺序在 Tailwind 中有断点时,子间距不起作用