css - 单击 SVG 元素时应用 CSS 样式

标签 css svg

我正在尝试为点击的元素设置 CSS 样式。我试图将 :active :clicked :targed 与类名放在一起,但这些都不起作用。 :hover 效果很好。感谢您的回答。

HTML:

<a (click)="Clicked(14)" class="lankstumas">
    <ellipse
    class="e-image"
       id="path3769-9"
       cx="43.089287"
       cy="103.09822"
       rx="43.845238"
       ry="39.498512"
       style="fill:#ff7f2a;stroke-width:0.26458332" />
    <text
    class="e-text"
       xml:space="preserve"
       style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332"
       x="22.300594"
       y="99.318459"
       id="text3836"><tspan
         sodipodi:role="line"
         id="tspan3834"
         x="22.300594"
         y="99.318459"
         style="stroke-width:0.26458332">LANKS - </tspan><tspan
         sodipodi:role="line"
         x="22.300594"
         y="112.54762"
         style="stroke-width:0.26458332"
         id="tspan3838">TUMAS</tspan></text>
         </a>

CSS:

.lankstumas:hover{
        .e-image{
            transition: .2s fill;
            fill: #FF8504!important; 
        }
        .e.text{
            transition: .2s fill;
            fill:#fff!important;
        }
        }

最佳答案

I am trying to set the CSS style for the clicked element.

实现此效果的一种方法是为元素提供一个 HTML5 Custom data-* 属性,如下所示:

data-clicked="false"

然后您可以使用 javascript 来检测对元素的点击并更新属性。

要使用 javascript 检测点击,请使用:

myElement.addEventListener('click', myFunction, false);

修改属性使用:

myElement.dataset.myAttribute = myValue;

工作示例:

const boxes = document.getElementsByClassName('box');

const showClick = (e) => {
  event.target.dataset.clicked = 'true';
}

for (let i = 0; i < boxes.length; i++) {

  boxes[i].addEventListener('click', showClick, false);


}
.box {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin: 6px;
  background-color: rgb(255, 0, 0);
  cursor: pointer;
}

.box::after {
  content: 'Click me!';
  display: block;
  text-align: center;
  line-height: 100px;
  color: rgb(255, 255, 255);
  font-weight: bold;
}

.box[data-clicked="true"] {
  color: rgb(255, 0, 0);
  background-color: rgb(255, 255, 0);
}

.box[data-clicked="true"]::after {
  content: 'Clicked!';
  color: rgb(255, 0, 0);
}
<div class="box" data-clicked="false"></div>
<div class="box" data-clicked="false"></div>
<div class="box" data-clicked="false"></div>
<div class="box" data-clicked="false"></div>
<div class="box" data-clicked="false"></div>

关于css - 单击 SVG 元素时应用 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58670120/

相关文章:

javascript - 克隆时 SVG 变黑

javascript - 在 SVG 元素中保留变换

javascript - 我需要为正在使用的 Accordion 更改颜色

javascript - firefox 中的动画元素会移动其他元素

javascript - 如何使用 jquery 创建图像幻灯片但具有背景图像属性?

javascript - 阻止嵌入式 SVG 在 Chrome 上捕获鼠标事件

javascript - 动态转换 SVG 的强大解决方案

javascript - 使表格的第一列始终可见

asp.net - 如何将以下 GridView 内联样式转换为样式表的类?

svg - 如何在 svg 中右对齐多个左对齐的 <tspan>?