首页 > 解决方案 > 多边形 onclick 事件的形状问题

问题描述

我已经用 4 个多边形(梯形)围绕它构建了一个正方形,我需要通过单击它来按顺序更改它的颜色。

我在网上找不到任何类似的问题。但我确实尝试zIndex过改变鼠标,但这不是一个好的解决方案。

您可以在此处检查的问题https://jsfiddle.net/d9Lh31sv/1/ 即使多边形 html 将其显示为矩形,并且正如您在此图像上看到的那样,它们在其两侧彼此重叠 重点

想知道是否有一种方法可以让点击事件只尊重它的多边形限制。在此先感谢。

	var objTrapezium = document.getElementsByClassName('trapezium');	
	if (objTrapezium) {		
		for (var i = 0; i < objTrapezium.length; i++) {
			objTrapezium[i].onclick = function() {
				var _Color = this.firstChild.nextSibling.attributes.fill.value;	
				_Color = _Color=="none"  ? "grey" :  _Color =="grey" ? "red":  _Color =="red" ? "green": _Color =="green" ?"blue": _Color =="blue" ? "grey": "";							
				this.firstChild.nextSibling.attributes.fill.value = _Color;
        
			};

			objTrapezium[i].onmouseover = function() {
				this.style.zIndex = 9999;
				this.style.backgroundColor = "lightsteelblue";
			  }
			objTrapezium[i].onmouseout = function(){
				this.style.zIndex = 1;
				this.style.backgroundColor = "transparent";
			  }


		}

	}
.trapezium{
	position: relative;
}
.square{
  left: 202px;
  width: 73px;
  height: 73px;
  top: 102px;
}
.bottom{
  left: 53px;
  top: 175px;
  z-index: 1;
}
.left{
  transform: rotate(90deg);
  left: -243px;
  top: 102px;
}
.right{
  transform: rotate(-90deg);
  left: -315px;
  top: 101px;
}
.top{
 transform: rotate(-180deg);
 left: 129px;
 top: -48px;
}
<div>
  <svg class="trapezium square">
    <rect stroke="black" fill="none" width="73" height="73" />				
  </svg>
  <svg class="trapezium bottom" height="72" width="217">
    <polygon stroke="black" fill="none" points="0,72 72,0 144,0 216,72" />
  </svg>
  <svg class="trapezium left" height="72" width="217">
    <polygon stroke="black" fill="none" points="0,72 72,0 144,0 216,72" />
  </svg>
  <svg class="trapezium right" height="72" width="217">
    <polygon stroke="black" fill="none" points="0,72 72,0 144,0 216,72" />
  </svg>
  <svg class="trapezium top" height="72" width="217">
    <polygon stroke="black" fill="none" points="0,72 72,0 144,0 216,72" />
  </svg>
</div>

 

标签: javascriptsvgpolygon

解决方案


正如我所评论的那样,我会以不同的方式做这件事:我会将所有内容放在一个 svg 元素中。请看一下。也许这就是你需要的。

svg{border:1px solid; width:300px}
use{fill:white;}
use:hover{fill:gold}
 <svg viewBox="-115 -115 230 230">
    <defs>
      <polygon id="poly" stroke="black"  points="-36.5,36.5 36.5,36.5 108, 108 -108,108 -36.5,36.5" transform="translate(0,3)"  />
    </defs>

    <use xlink:href="#poly" />
    <use xlink:href="#poly" transform="rotate(90)" /> 
    <use xlink:href="#poly" transform="rotate(180)" />
    <use xlink:href="#poly" transform="rotate(270)" />
    
    <rect stroke="black" fill="none" x="-35" y="-35" width="70" height="70" />	
    
  </svg>
  


推荐阅读