悬停并单击 CSS 三角形 [英] Hover and click on CSS triangle

查看:23
本文介绍了悬停并单击 CSS 三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 javascript 函数的三角形,可以移动该图像.

问题是元素有一个正方形,所以点击和悬停状态在三角形的外面触发(见下图中的红色部分):

如何防止在三角形外部悬停和单击,并仅在三角形内部允许单击/悬停状态?

解决方案

为了防止在 CSS 三角形外悬停和点击,您可以使用变换来制作三角形.

此处描述了此技术:

.tr {宽度:40%;填充底部:28.2842712474619%;/* = 宽度/sqrt(2) */位置:相对;溢出:隐藏;}.tr {位置:绝对;顶部:0;左:0;宽度:100%;高度:100%;背景颜色:rgba(0, 122, 199, 0.7);变换原点:0 100%;变换:旋转(45度);过渡:背景颜色 .3s;}/** 悬停效果 **/.tr a:悬停{背景:rgba(255, 165, 0, 0.7);}

<div class="tr"><a href="#"></a></div>

<小时>

另一种方法是使用带有可点击三角形的 SVG :

#tr{填充:透明;过渡:填充 0.3 秒;}#tr:悬停{填充:橙色;}/** 用于演示 **/html,body{height:100%;margin:0;填充:0;}body{background:url('https://farm8.staticflickr.com/7435/13629508935_62a5ddf8ec_c.jpg') 中心不重复;background-size:contain;}svg{display:block;width:30%;margin:0 auto;}

<a xlink:href="#"><polygon id="tr" points="50 0 100 60 0 60" fill="transparent" stroke="darkorange" stroke-width="2"/></a></svg>

I have a triangle with a javascript function that moves that image.

The issue is that the element has a square shape so click and hover state are triggered ouside the triangle (see the red part in following image) :

How can I prevent hover and click outside the triangle shape and allow click/hover state only inside the triangle shape?

解决方案

To prevent hover and click outside the CSS triangle you can use transforms to make the the triangle.

This technique is described here : CSS Triangles with transform rotate

The point is to use a wrapper with hidden overflow and rotate the clickable/hoverable element so that it actualy has a triangular shape and prevent the click event or hover state outside the triangle.

Demo: Click and hover on a CSS triangle

.tr {
  width: 40%;
  padding-bottom: 28.2842712474619%; /* = width / sqrt(2) */
  position: relative;
  overflow: hidden;
}
.tr a {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background-color: rgba(0, 122, 199, 0.7);
  transform-origin: 0 100%;
  transform: rotate(45deg);
  transition: background-color .3s;
}
/** hover effect **/
.tr a:hover {
  background: rgba(255, 165, 0, 0.7);
}

<div class="tr"><a href="#"></a></div>


Another approach would be to use an SVG with a clickable triangle :

#tr{
  fill:transparent;
  transition:fill .3s;
}
#tr:hover{
  fill: orange;
}

/** for the demo **/
html,body{height:100%;margin:0; padding:0;}
body{background:url('https://farm8.staticflickr.com/7435/13629508935_62a5ddf8ec_c.jpg') center no-repeat;background-size:contain;}
svg{display:block;width:30%;margin:0 auto;}

<svg viewbox="-2 -2 104 64">
  <a xlink:href="#">
    <polygon id="tr" points="50 0 100 60 0 60" fill="transparent" stroke="darkorange" stroke-width="2"/>
  </a>
</svg>

这篇关于悬停并单击 CSS 三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆