Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   MAP AREA конфликт двух функций (https://javascript.ru/forum/misc/83355-map-area-konflikt-dvukh-funkcijj.html)

Сергей Ракипов 22.11.2021 08:44

Проблема возникает именно в скрипит где зум, зум не работает

Сергей Ракипов 22.11.2021 08:52

Как я понял что проблема между скриптом подсветки и зумом

рони 22.11.2021 10:17

Цитата:

Сообщение от Сергей Ракипов
создана переменная и указана что за переменная, и что не так? что ему не нравится?

ему не нравится, что map не существует!!!
строка 120 пост #4

Сергей Ракипов 22.11.2021 10:20

Цитата:

Сообщение от рони (Сообщение 541741)
ему не нравится, что map не существует!!!
строка 120 пост #4

проблема не только в этом, если я даже уберу этот скрипт зумм не работает

Сергей Ракипов 22.11.2021 15:42

Конфликтует скрипт который находится а 125 строке с тем что на 85 строке

Сергей Ракипов 23.11.2021 06:32

Я правда не понимаю.
Вот есть две ошибки

test_3.html:98 Uncaught TypeError: Cannot read properties of null (reading 'getElementsByTagName')
at new ImageMap (test_3.html:98)
at window.onload (test_3.html:120)
ImageMap @ test_3.html:98
window.onload @ test_3.html:120
Объект load (асинхронный)
(анонимная) @ test_3.html:95


Хотя и с этими ошибками все работает.
Ну ладно говорят гугли, нахожу.

что не присвоены имена, присваиваю не чего не меняется.

нахожу вот такой ответ

document.getElementsByTagName('header')

Этот метод возвращает массив элементов, по которому нужно пробегаться циклом.

ну или взять первый
document.getElementsByTagName('header')[0].style.background = "url('img_tree.png')";

https://qna.habr.com/q/416081

присваиваю номер, не чего не меняется.

нахожу вот такой ответ

Потому, что скрипт срабатывает раньше загрузки разметки

https://javascript.ru/forum/misc/443...erty-null.html

но у меня скрипт этот идет после разметки

рони 23.11.2021 07:38

Сергей Ракипов,
imageMap = new ImageMap(document.getElementById('map_ID')
нет элемента с id = 'map_ID'
а раз нет элемента, значит и null нет свойства у пустоты getElementsByTagName

voraa 23.11.2021 07:46

Цитата:

Сообщение от Сергей Ракипов
Вот есть две ошибки

test_3.html:98 Uncaught TypeError: Cannot read properties of null (reading 'getElementsByTagName')
at new ImageMap (test_3.html:98)

Ошибка одна. В строке 98
Цитата:

Сообщение от Сергей Ракипов
Ну ладно говорят гугли, нахожу.

что не присвоены имена,

Не знаю, что вы гуглили.

По-русски это

Непойманная ошибка типа: Невозможно прочитать свойство у null (чтение 'getElementsByTagName')

Т.е в строке 98 вы пытаетесь сделать
null.getElementsByTagName

Смотрим строку 98, там map.getElementsByTagName('area')
Т.е. map === null

Остается выяснить, почему?

Сергей Ракипов 23.11.2021 07:49

рони,
Спасибо, понял.

Все исправил ошибок нет, но не работает.

<!doctype html>
<html lang="ru">
<head>
	<meta charset="utf-8">
	<title>index</title>
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<style>
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}
		.blok {
			margin: 40px auto 0px;
			max-width: 900px;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
		}
		.karta {
			width: 100%;
			height: 400px;
			cursor: crosshair;
			overflow: hidden;
			padding: 0;
			margin: 0;
			touch-action: none;
			border: 10px solid #7F7F7F;
		}
		.karta img {
			padding: 0;
			margin: 0;
			display: block;
		}
		.upravlenie_blok {
			width: 148px;
			height: 54px;
			margin: 40px auto 0px;
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 10px 10px 10px 10px;
		}
		.plus {
			width: 54px;
			height: 54px;
			cursor: pointer;
			margin: 0px 20px 0px 0px;
			background-image: url(https://rakipov.ru/files/plus_ikonka.svg);
			background-repeat: no-repeat;
			background-position: center;
			background-size: 95%;
		}
		.minus {
			width: 54px;
			height: 54px;
			cursor: pointer;
			background-image: url(https://rakipov.ru/files/minus_ikonka.svg);
			background-repeat: no-repeat;
			background-position: center;
			background-size: 95%;
		}
		.minus.dis,
		.plus.dis {
			opacity: .2;
		}
	</style>
	<script  type="text/javascript"  src="https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
<div class="blok">
	<div class="karta">
		<img src="https://rakipov.ru/files/map.jpg" id="img_ID" usemap="#619b0da354566" alt="">
	</div>
	<div class="upravlenie_blok">
		<div class="plus dis"></div>
		<div class="minus"></div>
	</div>
</div>
<map id="map_ID" name="619b0da354566"><area shape="poly" href="/#0" coords="385,734,385,753,422,753,459,753,459,734,459,715,422,715,385,715"><area shape="poly" href="/#1" coords="78,703,78,764,154,764,230,764,230,703,230,642,214,642,198,643,197,689,197,736,153,736,109,736,109,690,109,643,104,643,99,642,88,642,78,641"><area shape="poly" href="/#2" coords="839,634,838,636,838,702,839,768,854,768,870,768,870,701,870,633,855,633,839,633"><area shape="poly" href="/#3" coords="726,634,725,636,725,702,726,768,741,768,757,768,757,701,757,633,742,633,726,633"><area shape="poly" href="/#4" coords="610,634,609,636,609,702,610,768,625,768,641,768,641,701,641,633,626,633,610,633"><area shape="poly" href="/#5" coords="462,605,451,616,475,640,499,665,499,715,499,766,514,766,529,766,529,707,529,649,501,621,474,593"><area shape="poly" href="/#6" coords="338,621,310,649,310,707,311,766,326,766,341,766,341,715,341,665,365,641,389,617,377,605,366,593"><area shape="poly" href="/#7" coords="404,553,387,570,404,586,421,603,437,586,454,570,437,553,421,536"><area shape="poly" href="/#8" coords="937,561,937,596,963,596,989,596,990,595,990,594,1001,561,1012,527,1002,527,993,527,965,526,937,526"><area shape="poly" href="/#9" coords="496,465,475,487,496,508,518,529,539,508,560,487,539,465,518,444"><area shape="poly" href="/#10" coords="984,434,945,435,940,435,936,435,936,470,936,504,976,504,1017,504,1027,470,1038,436,1038,434,1038,433,1030,433,1023,433"><area shape="poly" href="/#11" coords="776,502,777,574,840,574,903,574,903,514,903,453,902,453,901,453,889,458,877,463,876,504,876,545,846,545,815,545,815,501,815,457,831,457,848,457,848,452,849,447,849,439,849,431,813,431,776,431"><area shape="poly" href="/#12" coords="581,429,580,431,580,460,581,489,611,489,641,489,641,459,641,429,611,428,581,428"><area shape="poly" href="/#13" coords="136,356,111,382,111,383,111,384,184,454,257,525,258,525,259,525,284,499,309,473,309,472,309,471,235,401,162,331,161,330,161,330"><area shape="poly" href="/#14" coords="879,313,878,313,878,329,878,344,938,344,998,344,998,346,999,347,999,353,999,359,1012,359,1025,359,1025,336,1025,313,952,312,879,312"><area shape="poly" href="/#15" coords="531,324,531,343,580,343,629,343,629,324,629,304,580,304,531,304"><area shape="poly" href="/#16" coords="777,331,777,360,798,360,819,360,819,331,819,303,798,302,777,302"><area shape="poly" href="/#17" coords="669,303,668,305,668,332,669,360,689,360,710,360,710,331,710,302,690,302,669,302"><area shape="poly" href="/#18" coords="878,206,879,222,938,222,997,222,998,223,999,225,999,231,999,237,1012,237,1025,237,1025,213,1025,190,952,190,878,190"><area shape="poly" href="/#19" coords="531,206,531,225,580,225,629,225,629,206,629,186,580,186,531,186"><area shape="poly" href="/#20" coords="672,198,672,224,690,224,707,224,707,198,707,172,689,171,672,171"><area shape="poly" href="/#21" coords="784,204,784,237,802,237,820,237,820,218,820,198,817,198,814,198,814,184,814,171,799,170,784,170"><area shape="poly" href="/#22" coords="283,176,283,194,327,194,372,194,412,235,453,276,453,323,453,369,472,369,490,369,490,315,490,262,439,210,387,159,335,158,283,158"><area shape="poly" href="/#23" coords="1110,96,1099,105,1099,106,1099,107,1119,130,1139,152,1139,153,1139,154,1112,178,1086,202,1086,204,1086,205,1094,215,1103,226,1104,226,1105,226,1143,190,1181,154,1180,152,1179,150,1150,118,1121,86,1121,86,1120,86"><area shape="poly" href="/#24" coords="531,87,531,106,580,106,629,106,629,87,629,67,580,67,531,67"><area shape="poly" href="/#25" coords="980,89,980,117,1001,117,1021,117,1021,89,1021,61,1001,61,980,61"><area shape="poly" href="/#26" coords="884,62,883,62,883,90,883,117,904,117,925,117,925,89,925,61,904,61,884,61"><area shape="poly" href="/#27" coords="786,89,786,117,807,117,827,117,827,89,827,61,807,61,786,61"><area shape="poly" href="/#28" coords="668,89,668,117,689,117,709,117,709,89,709,61,689,61,668,61"><area shape="poly" href="/#29" coords="78,69,78,130,95,130,111,130,111,69,111,7,94,7,78,7"></map>

<script src="https://cdn.jsdelivr.net/npm/imagemapster@1.5.4/dist/jquery.imagemapster.min.js"></script>
<script>
	$("img[usemap]").mapster({
	scaleMap: true,
	fill: true,
	fillColor: '2CA7DC',
	fillOpacity: 0.75,
	});
</script>
<script>
	window.onload = function () {
		var ImageMap = function ( map, img ) {
				var n,
					areas = map.getElementsByTagName( 'area' ),
					len = areas.length,
					coords = [],
					previousWidth = 128;
				for ( n = 0; n < len; n++ ) {
					coords[ n ] = areas[ n ].coords.split( ',' );
				}
				this.resize = function () {
					var n, m, clen,
						x = img.offsetWidth / previousWidth;
					for ( n = 0; n < len; n++ ) {
						clen = coords[ n ].length;
						for ( m = 0; m < clen; m++ ) {
							coords[ n ][ m ] *= x;
						}
						areas[ n ].coords = coords[ n ].join( ',' );
					}
					previousWidth = document.body.clientWidth;
					return true;
				};
				window.onresize = this.resize;
			},
			imageMap = new ImageMap( document.getElementById( 'map_ID' ), document.getElementById( 'img_ID' ) );
		imageMap.resize();
		return;
}
</script>

<script>
	document.addEventListener("DOMContentLoaded", function() {

		document.querySelectorAll('.karta').forEach(el => {
			let _startX, _startY, _scrollLeft, _scrollTop, max_width, max_height, min_width, min_height;


			const pointerHandler = (event) => {
				const {
					screenX,
					screenY
				} = event;

				if (event.type === "pointerdown") {
					document.addEventListener("pointermove", pointerHandler);
					document.addEventListener("pointerup", pointerHandler);

					_startX = screenX;
					_startY = screenY;

					_scrollLeft = el.scrollLeft;
					_scrollTop = el.scrollTop;
				}

				if (event.type === "pointerup") {
					document.removeEventListener("pointermove", pointerHandler);
					document.removeEventListener("pointerup", pointerHandler);
				}

				if (event.type === "pointermove") {
					const dx = (screenX - _startX);
					const dy = (screenY - _startY);

					el.scrollTo(
						_scrollLeft - dx,
						_scrollTop - dy
					);
				}

				event.preventDefault();
			}

			el.addEventListener("pointerdown", pointerHandler);
			let img = el.querySelector("img");
			let ratio = max_ratio = 10;
			const zoom = _ => {  console.log(el.scrollLeft)
				let _w = img.width, _h = img.height;
				img.width = min_width + (max_width - min_width) * ratio / max_ratio;
				img.height = img.width * (max_height / max_width);
				_w -= img.width; _h -= img.height;
				_w = el.scrollLeft - _w/2; _h = el.scrollTop - _h/2;
				el.scrollTo( _w, _h );
			}
			const _load = _ => {
				max_width = img.naturalWidth;
				max_height = img.naturalHeight;
				min_width = el.clientWidth;
				el.style.height = Math.trunc(min_width * (max_height / max_width)) + "px";
				min_height = el.clientHeight;

				el.scrollTo(
					(max_width - min_width) / 2,
					(max_height - min_height) / 2
				);
			}
			img.complete ? _load() : img.addEventListener("load", _load);
			let nav = el.nextElementSibling;

			nav.addEventListener("pointerdown", ({
				target
			}) => {
				if (target = target.closest(".plus, .minus")) {
				ratio += target.classList.contains("plus") ? 1 : -1;
				ratio = Math.max(0, Math.min(ratio, max_ratio));
				nav.querySelector(".plus").classList.toggle("dis", ratio === max_ratio);
				nav.querySelector(".minus").classList.toggle("dis", !ratio);
				zoom();
				}
			});
		})
	});
</script>

</body>
</html>

voraa 23.11.2021 07:55

Цитата:

Сообщение от Сергей Ракипов
нахожу вот такой ответ

Потому, что скрипт срабатывает раньше загрузки разметки

У вас скрипты вызываются один по

window.onload

Другой по

document.addEventListener("DOMContentLoaded"

Эти события происходят после загрузки разметки и построения DOM.
Но второй скрипт выполнится первым, т.к. событие DOMContentLoaded происходит раньше load

Но в донном случае это ни на что не влияет.


Часовой пояс GMT +3, время: 07:47.