javascript - 多边形 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>
解决方案
正如我所评论的那样,我会以不同的方式做这件事:我会将所有内容放在一个 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>
推荐阅读
- php - 使用 ajax 嵌套资源控制器和路由
- excel - 显示打印对话框
- next.js - 每次重新加载 nextjs 材料 ui 样式丢失甚至添加材料 ui nextjs github 存储库的 _app.js 和 _document.js 但重新加载样式后仍然丢失
- node.js - 为下一个连接设置路由页面
- r - 将模型列表(randomForest)应用于 data.frames 列表以获取因素列表
- maven-3 - Maven项目重复依赖警告
- javascript - 将所有 onclick 更改为事件侦听器
- airflow - 气流 - 远大的期望 - 获取/设置配置变量
- ssl - 在应用启动时从 SSL 认证验证中禁用 Kestrel
- javascript - 单击主页以外的其他选项卡时Material-ui选项卡指示器消失