无法使点击事件侦听器在svg元素上工作

时间:2019-07-01 10:58:52

标签: javascript html css

我有一个svg文本元素。我在文本上实现了一个onclick事件,以便每次单击文本时它都会变得更大。不知何故,它不起作用。

CSS:

 <style>
            html,
            body {
                height: 100%;
                margin: 0;
            }

            .container {
                background-color: yellow;
                z-index: 7;
                height: 100%;
                width: 100%;
                position: absolute;
                opacity: .5;
            }

            .textBox {
                background-color: blue;
                position: absolute;
                bottom: 10px;
                left: 0px;
                right: 0px;
            }

            #text1 {
                animation-name: diamondOrigin;
                animation-duration: 8s;
                animation-fill-mode: forwards;
            }

            @keyframes diamondOrigin {
                from {
                    transform: scale(1);
                }

                to {
                    transform: scale(300);
                }
            }
 </style>

HTML:

    <div class="textBox">
        <p>fljsfa</p>
    </div>

    <div class="container">
        <svg height="100%" width="100%">    
              <text id="text1" onclick="grow()" x="0" y="10" fill="red">I love SVG</text>
        </svg>
    </div>

JS:

 <script>
       function grow() {
                    var changeText = document.getElementById("text1");
                    var compStyles = window.getComputedStyle(changeText);
                    changeText.textContent = 'Works?';
                }
        grow();
 </script>

1 个答案:

答案 0 :(得分:0)

您直接将css动画应用于元素,并且单击功能正常运行,因为文本更改为“ Works”,

这是解决方案

function grow(e) {
   e.classList.add('text1');
}
html,
body {
    height: 100%;
    margin: 0;
}

.container {
    background-color: yellow;
    z-index: 7;
    height: 100%;
    width: 100%;
    position: absolute;
    opacity: .5;
}

.textBox {
    background-color: blue;
    position: absolute;
    bottom: 10px;
    left: 0px;
    right: 0px;
}

.text1 {
    animation-name: diamondOrigin;
    animation-duration: 8s;
    animation-fill-mode: forwards;
}

@keyframes diamondOrigin {
    from {
        transform: scale(1);
    }

    to {
        transform: scale(300);
    }
}
<div class="textBox">
    <p>fljsfa</p>
</div>
    
<div class="container">
    <svg height="100%" width="100%">
     <text id="text1" onclick="grow(this)" x="0" y="10" fill="red">I love SVG</text> 
  </svg>
</container>