【发布时间】:2019-07-03 16:21:34
【问题描述】:
我用 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>
【问题讨论】:
-
我会采取不同的做法:我会将所有内容放在一个 svg 元素中。此外,您正在尝试设置
background-color。在 SVG 中,您需要设置fill -
我这样做
background-color只是为了表明他们互相超越......
标签: javascript svg polygon