Как прикрепить события мыши к скрытым элементам SVG? - PullRequest
0 голосов
/ 16 мая 2018

У меня есть тег <rect> внутри <svg>, и вместо установки свойства visibility : hidden; css на прямоугольник я просто применяю stroke : none; fill : none; к нему. Но событие onclick сейчас не вызывается. Есть ли способ получить onclick на невидимый прямоугольник в SVG? Я делюсь своим кодом. Часть JavaScript встроена в HTML.

Заранее спасибо.

<html>
	<head>
		<title>Demo</title>
	</head>
	
	<body>
		<svg id = "oSvg" height = "900" width = "1200"></svg>
		<script>
			var svgns = "http://www.w3.org/2000/svg";
			var rect = document.createElementNS(svgns, "rect");
			rect.setAttributeNS(null, 'x', 100);
			rect.setAttributeNS(null, "y", 200);
			rect.setAttributeNS(null, "width", "200");
			rect.setAttributeNS(null, "height", "300");
			rect.setAttributeNS(null, "transform", "matrix(1, 0, 0, 1, 0, 0)");
			rect.setAttributeNS(null, 'style', 'stroke:none; fill : none;')
			rect.setAttributeNS(null, 'onclick', 'console.log("Rect click");');
			document.getElementById("oSvg").appendChild(rect);
		</script>
	</body>
</html>

Также пробовал тот же код с jQuery, но не смог найти решение

<html>
	<head>
		<title>Demo</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	</head>
	
	<body>
		<svg id = "oSvg" height = "900" width = "1200"></svg>
		<script>
			var svgns = "http://www.w3.org/2000/svg";
			var rect = document.createElementNS(svgns, "rect");
			rect.setAttributeNS(null, 'x', 100);
			rect.setAttributeNS(null, "y", 200);
			rect.setAttributeNS(null, "width", "200");
			rect.setAttributeNS(null, "height", "300");
			rect.setAttributeNS(null, "transform", "matrix(1, 0, 0, 1, 0, 0)");
			rect.setAttributeNS(null, 'style', 'stroke:none; fill : none;')
			document.getElementById("oSvg").appendChild(rect);
			$(rect).on('click', function() {
				console.log("hello");
			});
		</script>
	</body>
</html>

Ответы [ 2 ]

0 голосов
/ 16 мая 2018

Вместо fill: none я использовал opacity: 0.И это работает.Пожалуйста, дайте мне знать, если это хорошо для вас.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
	<head>
		<title>Demo</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	</head>
	
	<body>
		<svg id = "oSvg" height = "900" width = "1200"></svg>
		<script>
			var svgns = "http://www.w3.org/2000/svg";
			var rect = document.createElementNS(svgns, "rect");
			rect.setAttributeNS(null, 'x', 100);
			rect.setAttributeNS(null, "y", 200);
			rect.setAttributeNS(null, "width", "200");
			rect.setAttributeNS(null, "height", "300");
			rect.setAttributeNS(null, "transform", "matrix(1, 0, 0, 1, 0, 0)");
			rect.setAttributeNS(null, 'style', 'stroke:none; opacity: 0;')
			document.getElementById("oSvg").appendChild(rect);
			$(rect).on('click', function() {
				console.log("hello");
			});
		</script>
	</body>
</html>
0 голосов
/ 16 мая 2018

Значение по умолчанию для событий указателя равно visiblePainted, в котором, если вы удалите и обводку, и заливку фигуры svg, для события указателя не останется ничего, чтобы завершиться.

Таким образом, вы должны явно установить visibleFill, visible, fill или all, если хотите продолжать использовать fill="none".

document.querySelector('rect').onclick = function(){
  console.log('clicked on the rect');
}
svg {border: 1px solid;}
<svg>
<rect pointer-events="all" fill="none" x="0" y="0" width="300" height="150"/>
</svg>

В качестве альтернативы, вы можете установить прозрачную заливку. (Мне сказали, что это не очень хорошая идея, даже если она будет работать ...)

Также обратите внимание, что

  • setAttributeNS(null,... это просто setAttribute(...
  • добавление прослушивателей событий в качестве атрибута крайне не рекомендуется, поскольку это означает, что вы сможете запускать только обратные вызовы из глобальной области видимости.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...